条件分岐でgoogle mapのiconを変える

コンサル会社で、外資系のコンサルだけアイコンを変えてみます。
アイコンはsetOptionで変えます。
setOptions({
icon: {
url: icon
}
});

var map;
var marker = [];
var infoWindow = [];
var icon = 'icon.png';
var markerData = [
  {
       name: 'マッキンゼー',
       ref: '外資',
       lat: 35.6636921,
    lng: 139.7418055
 }, {
        name: 'ベイン',
        ref: '外資',
     lat: 35.6661276,
        lng: 139.7312397
 }, {
        name: 'アビーム',
        ref: '外資',
     lat: 35.6844514,
      lng: 139.764942
 }, {
        name: 'ボスコン',
        ref: '外資',
        lat: 35.6811759,
        lng: 139.734872
 }, {
        name: '野村総研',
        ref: '国内',

     lat: 35.6884676,
     lng: 139.7645002
 }, {
        name: 'MUFJリサーチ',
        ref: '国内',
       lat: 35.6618341,
     lng: 139.7443247
 }
];

function initMap(){
    var mapLatLng = new google.maps.LatLng({ lat: markerData[0]['lat'], lng: markerData[0]['lng']});
    map = new google.maps.Map(document.getElementById('sample'),{
        center: mapLatLng,
        zoom: 14
    });

    for(var i=0; i < markerData.length; i++){
        markerLatLng = new google.maps.LatLng({lat: markerData&#91;i&#93;&#91;'lat'&#93;, lng: markerData&#91;i&#93;&#91;'lng'&#93;});
        marker&#91;i&#93; = new google.maps.Marker({
            position: markerLatLng,
            map: map
        });

        infoWindow&#91;i&#93; = new google.maps.InfoWindow({
            content: '<div class="sample">' + markerData[i]['name'] + '</div>'
        });

        if(markerData[i]['ref'] == '外資'){
            marker[i].setOptions({
                icon: {
                    url: icon
                }
            });
        }
        markerEvent(i);
    }
    
}

function markerEvent(i){
    marker[i].addListener('click', function(){
        infoWindow[i].open(map, marker[i]);
    });
}

なるほど、大分わかってきましたね。

位置情報

読み取り専用のNavigator.geolocationは、ウェブコンテンツがデバイスの位置情報にアクセスするためのGeolocationオブジェクトを返す。


<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      #map {
        height: 50%;
        margin-top: 10px;
      }
      html, body {
        height: 100%;
        margin: 10px;
        padding: 0;
      }
    </style>
  </head>
  <body>
  	<div id="map"></div>
  	<script>


      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 2
        });
        var infoWindow = new google.maps.InfoWindow({map: map});

        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
      }
    </script>
  	<script async defer
src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap">
</script>
</body>
</html>

一通り終わったと思ったらこれか?
なるほど、navigator.geolocation.getCurrentPositionで位置情報を取得していますね。

<script>

var options = {
	enableHighAccuracy : true,
	timeout: 5000,
	maximumAge: 0
};

function success(pos){
	var crd = pos.coords;

	console.log('your current position is:');
	console.log('latitude : ' + crd.latitude);
	console.log('longitude: ' + crd.longitude);
	console.log('More or less ' + crd.accuracy + ' meters');
};

function error(err){
	console.warn('ERROR(' + err.code + '):' + err.message);
};

navigator.geolocation.getCurrentPosition(success, error, options);
</script>

heatmap

つくってる人凄すぎてコーディングが嫌になるな。。


<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      #map {
        height: 50%;
        margin-top: 10px;
      }
      html, body {
        height: 100%;
        margin: 10px;
        padding: 0;
      }
    </style>
  </head>
  <body>
  	<div id="map"></div>
  	<script>
  	var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 2,
          center: {lat: -33.865427, lng: 151.196123},
          mapTypeId: 'terrain'
        });


      var script = document.createElement('script');

      script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
        document.getElementsByTagName('head')[0].appendChild(script);

      }

      function eqfeed_callback(results) {
        var heatmapData = [];
        for (var i = 0; i < results.features.length; i++) {
          var coords = results.features&#91;i&#93;.geometry.coordinates;
          var latLng = new google.maps.LatLng(coords&#91;1&#93;, coords&#91;0&#93;);
          heatmapData.push(latLng);
        }
        var heatmap = new google.maps.visualization.HeatmapLayer({
          data: heatmapData,
          dissipating: false,
          map: map
        });
      }
      // // window.eqfeed_callback = function(results) {
      // //   for (var i = 0; i < results.features.length; i++) {
      // //     var coords = results.features&#91;i&#93;.geometry.coordinates;
      // //     var latLng = new google.maps.LatLng(coords&#91;1&#93;,coords&#91;0&#93;);
      // //     var marker = new google.maps.Marker({
      // //       position: latLng,
      // //       map: map
      // //     });
      // //   }
      // }
    </script>
  	<script async defer
src="https://maps.googleapis.com/maps/api/js?key=hoge&libraries=visualization&callback=initMap">
</script>
</body>
</html>

データの可視化


<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      #map {
        height: 50%;
        margin-top: 10px;
      }
      html, body {
        height: 100%;
        margin: 10px;
        padding: 0;
      }
    </style>
  </head>
  <body>
  	<div id="map"></div>
  	<script>
  	var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 2,
          center: {lat: -33.865427, lng: 151.196123},
          mapTypeId: 'terrain'
        });

      var script = document.createElement('script');
      script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
        document.getElementsByTagName('head')[0].appendChild(script);

        map.data.setStyle(function(feature) {
          var magnitude = feature.getProperty('mag');
          return {
            icon: getCircle(magnitude)
          };
        });
      }

      function getCircle(magnitude) {
        return {
          path: google.maps.SymbolPath.CIRCLE,
          fillColor: 'red',
          fillOpacity: .2,
          scale: Math.pow(2, magnitude) / 2,
          strokeColor: 'white',
          strokeWeight: .5
        };
      }

      function eqfeed_callback(results) {
        map.data.addGeoJson(results);
      }


      // // window.eqfeed_callback = function(results) {
      // //   for (var i = 0; i < results.features.length; i++) {
      // //     var coords = results.features&#91;i&#93;.geometry.coordinates;
      // //     var latLng = new google.maps.LatLng(coords&#91;1&#93;,coords&#91;0&#93;);
      // //     var marker = new google.maps.Marker({
      // //       position: latLng,
      // //       map: map
      // //     });
      // //   }
      // }
    </script>
  	<script async defer
src="https://maps.googleapis.com/maps/api/js?key=notwatch&callback=initMap">
</script>
</body>
</html>

住所からGoogle mapに2つのラベルを表示する

なんとなく、それらしいものができてきました。中心のポジションは、緯度経度の平均を取ってます。
あ、array_sum, countでできますね。
$lat_a = array_sum($lat)/count($lat);
$lng_a = array_sum($lng)/count($lng);

<?php

$resutaurant = array(
    "Brasserie de L'institut" => "東京都新宿区市谷船河原町15",
    "Le Mange-Tout" => '東京都新宿区納戸町22'
  );
function urlencode_rfc3986($str){
  return str_replace('%7E','~', rawurlencode($str));
}
$i = 0;
foreach($resutaurant as $name => $address){
  $encode_address = urlencode_rfc3986($address);

  $url = 'http://maps.google.com/maps/api/geocode/json?address='. $encode_address.'&sensor=false';
  $json = file_get_contents($url);
  $obj = json_decode($json,true);

  $lat[] = $obj["results"]["0"]["geometry"]["location"]["lat"];
  $lng[] = $obj["results"]["0"]["geometry"]["location"]["lng"];
  echo $name ." ".$address .'<br>';
  echo $lat[$i] ." " .$lng[$i]. "<br>";
  $rname[] = $name;
  $i++;
}

$lat_a = ($lat[0]+$lat[1])/2;
$lng_a = ($lng[0]+$lng[1])/2;


?>
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      #map {
        height: 50%;
        margin-top: 10px;
      }
      html, body {
        height: 100%;
        margin: 10px;
        padding: 0;
      }
    </style>
  </head>
  <body>
  	<div id="map"></div>
  	<script>
  	var map;
  	function initMap(){
      var position = {lat: <?php echo $lat_a; ?>, lng: <?php echo $lng_a; ?>};
  		map = new google.maps.Map(document.getElementById('map'),{
  			center: position,
  			zoom: 16
  		});

      var labels = ["<?php echo $rname&#91;0&#93;; ?>","<?php echo $rname&#91;1&#93;; ?>"];

      var markers = locations.map(function(location, i) {
          return new google.maps.Marker({
            position: location,
            label: labels[i]
          });
        });

      var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
      }

    var locations = [
    {lat: <?php echo $lat&#91;0&#93;; ?>, lng: <?php echo $lng&#91;0&#93;; ?>},
    {lat: <?php echo $lat&#91;1&#93;; ?>, lng: <?php echo $lng&#91;1&#93;; ?>}
    ]
  	</script>
    <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
    </script>
  	<script async defer
src = "https:maps.googleapis.com/maps/api/js?key=hogehogek&callback=initMap">
</script>
</body>
</html>

住所からlat, lngを抽出して地図を表示

飯田橋のBrasserie de L’institutを表示してみましょう。
住所は、東京都新宿区市谷船河原町15。
google map apiのjsonでlat, lngを取得します。

jsのマップを表すクラスはMap, centerとzoomは必須。
callbackで、apiを読み込んだ後のinitMap()実行を指定しています。

<?php

$name = "Brasserie de L'institut";
$address = '東京都新宿区市谷船河原町15';
function urlencode_rfc3986($str){
  return str_replace('%7E','~', rawurlencode($str));
}
$encode_address = urlencode_rfc3986($address);

$url = 'http://maps.google.com/maps/api/geocode/json?address='. $encode_address.'&sensor=false';
$json = file_get_contents($url);
$obj = json_decode($json,true);

$lat = $obj&#91;"results"&#93;&#91;"0"&#93;&#91;"geometry"&#93;&#91;"location"&#93;&#91;"lat"&#93;;
$lng = $obj&#91;"results"&#93;&#91;"0"&#93;&#91;"geometry"&#93;&#91;"location"&#93;&#91;"lng"&#93;;
echo $name ." ".$address .'<br>';
echo $lat ." " .$lng;

?>
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      #map {
        height: 50%;
        margin-top: 10px;
      }
      html, body {
        height: 100%;
        margin: 10px;
        padding: 0;
      }
    </style>
  </head>
  <body>
  	<div id="map"></div>
  	<script>
  	var map;
  	function initMap(){
  		map = new google.maps.Map(document.getElementById('map'),{
  			center:{lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>},
  			zoom: 16
  		});
  	}
  	</script>
  	<script async defer
src = "https:maps.googleapis.com/maps/api/js?key=hogehoge&callback=initMap">
</script>
</body>
</html>

var markerを追加して、ラベルを付与できる。

   var map;
  	function initMap(){
      var position = {lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>};
  		map = new google.maps.Map(document.getElementById('map'),{
  			center: position,
  			zoom: 16
  		});
      var marker = new google.maps.Marker({
        position: position,
        map: map
      });
  	}

google map api

すご

<!DOCTYPE html>
<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" >
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<title>Using Google Maps</title>
	<style>
	#map {
		height: 100%;
	}
	html, body {
		height: 100%;
		margin: 0;
		padding: 0;
	}
	</style>
</head>
<body>
	<div id="map"></div>

	<script>
		var customLabel = {
			restaurant: {
				label: 'R'
			},
			bar: {
				label: 'B'
			}
		};

		function initMap(){
			var map = new google.maps.Map(document.getElementById('map'),{
				center: new google.maps.LatLng(-33.863276, 151.207977),
				zoom: 12
			});
			var infoWindow = new google.maps.InfoWindow;

			downloadUrl('mapmaker.php', function(data){
				var xml = data.responseXML;
				var markers = xml.documentElement.getElementsByTagName('marker');
				Array.prototype.forEach.call(markers, function(markerElem){
					var name = markerElem.getAttribute('name');
					var address = markerElem.getAttribute('address');
					var type = markerElem.getAttribute('type');
					var point = new google.maps.LatLng(
						parseFloat(markerElem.getAttribute('lat')),
						parseFloat(markerElem.getAttribute('lng')));

					var infowincontent = document.createElement('div');
					var strong = document.createElement('strong');
					strong.textContent = name
					infowincontent.appendChild(strong);
					infowincontent.appendChild(document.createElement('br'));

					var text = document.createElement('text');
					text.textContent = address
					infowincontent.appendChild(text);
					var icon = customLabel[type] || {};
					var marker = new google.maps.Marker({
						map: map,
						position: point,
						label: icon.label
					});
					marker.addListener('click', function(){
						infoWindow.setContent(infowincontent);
						infoWindow.open(map, marker);
					});
				});
			});
		}

function downloadUrl(url, callback){
	var request = window.ActiveXObject ?
		new ActiveXObject('Microsoft.XMLHTTP') :
		new XMLHttpRequest;

	request.onreadystatechange = function(){
		if (request.readyState == 4){
			request.onreadystatechange = doNothing;
			callback(request, request.status);
		}
	};

	request.open('GET', url, true);
	request.send(null);
}

function doNothing(){}
</script>
<script async defer
src = "https:maps.googleapis.com/maps/api/js?key=hogehoge&callback=initMap">
</script>
</body>
</html>

ISO 3166-1 alpha-2

ISO 3166-1は、IOSによって発行されている国のコード。
alpha-2は、ラテン文字2文字で、alpha-3はラテン文字3文字。


United States 840 USA US
United Kingdom 826 GBR GB
India 356 IND IN
Japan 392 JPN JP
France 250 FRA FR