前提・実現したいこと
googleMapAPIでgoogle.maps.Geocoder()を使って取得した複数の座標それぞれにピンを表示させようとしています。
現状ではピンは一つだけ、リロードのたびに位置が指定されたうちのどれかに移動します。
検索して出てくるのは経度緯度を直接打ち込んでいて、google.maps.Geocoder()で取得するものがなく、非同期と関わりがあるのかといったところから分かりませんでした。
詳しい方ご教授お願いします。
該当のソースコード
javaScript
1var geocoder;//住所から座標を取得 2var latlng;//住所から緯度経度を取得 3var map; 4var marker = []; 5 6 7var markerData = [ // マーカーを立てる場所名・住所 8 { 9 name: '東京タワー', 10 address: "東京都港区芝公園4丁目2−8" 11 }, { 12 name: '増上寺', 13 address: "東京都港区芝公園4丁目7−35" 14 }, { 15 name: '東京プリンスホテル', 16 address: "東京都港区芝公園3丁目3−1" 17 } 18]; 19 20 21function initMap() { 22 geocoder = new google.maps.Geocoder();//座標取得の準備 23 var address = document.getElementById( "address" ).value;//住所 24 25 for (var i = 0; i < markerData.length; i++) {//ピンを多数立てるためにリストの数だけ回す 26 geocoder.geocode({ 27 "address" : markerData[i].address 28 }, function(results, status) { // 結果 29 if (status === google.maps.GeocoderStatus.OK) { // ステータスがOKの場合 30 var bounds = new google.maps.LatLngBounds(); 31 latlng = results[0].geometry.location; 32 bounds.extend(latlng); 33 34 map = new google.maps.Map(document.getElementById('map'), { 35 zoom: 15, 36 center: latlng 37 }); 38 39 // //マーカーを立てる 40 marker[i] = new google.maps.Marker({ 41 position: latlng, 42 map: map 43 }); 44 45 } else { // 失敗した場合 46 console.group('Error'); 47 console.log(results); 48 console.log(status); 49 } 50 }); 51 } 52}
解決時のソースコード
解決いたしました。mapに適当な初期値を入れて初期化しておくと上手くできました。
javaScript
1//markerDataまでは同じです。 2 3//この関数でmapを初期化しておきます。 4//Google Maps PlatformドキュメントのMaps JavaScript API/Geocodingに掲載されているものです。 5 6function initialize() { 7 geocoder = new google.maps.Geocoder(); 8 var latlng = new google.maps.LatLng(-34.397, 150.644); 9 var mapOptions = { 10 zoom: 14, 11 center: latlng 12 } 13 map = new google.maps.Map(document.getElementById('map'), mapOptions); 14} 15 16function initMap() { 17 18 initialize();//マップの初期化 19 20 for (let i = 0; i < markerData.length; i++) {//ピンを多数立てるためにリストの数だけ回す 21 geocoder.geocode({ 22 "address" : markerData[i].address 23 }, function(results, status) { // 結果 24 if (status === google.maps.GeocoderStatus.OK) { // ステータスがOKの場合 25 let bounds = new google.maps.LatLngBounds(); 26 latlng = results[0].geometry.location; 27 bounds.extend(latlng); 28 29 //簡易的にしていますが本来はマップの中心に持ってきたい座標でのみmap.setCenter(latlng);をするべきだと思います。 30 if(i === 0){ 31 map.setCenter(latlng); 32 } 33 34 //マーカーを立てる 35 marker[i] = new google.maps.Marker({ 36 position: latlng, 37 map: map 38 }); 39 40 } else { // 失敗した場合 41 console.group('Error'); 42 console.log(results); 43 console.log(status); 44 } 45 46 }); 47 } 48}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/12/14 08:06
2019/12/14 09:32
2019/12/14 13:07
2019/12/14 13:21
2019/12/14 13:34 編集
2019/12/14 14:02
2019/12/15 02:51 編集