teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

解決しましたがソースコードが長いので追記させていただきます。

2019/12/15 02:43

投稿

masahirori
masahirori

スコア5

title CHANGED
File without changes
body CHANGED
@@ -14,7 +14,7 @@
14
14
  var marker = [];
15
15
 
16
16
 
17
- var markerData = [ // マーカーを立てる場所名・緯度・経度
17
+ var markerData = [ // マーカーを立てる場所名・住所
18
18
  {
19
19
  name: '東京タワー',
20
20
  address: "東京都港区芝公園4丁目2−8"
@@ -60,4 +60,57 @@
60
60
  });
61
61
  }
62
62
  }
63
+ ```
64
+
65
+ ### 解決時のソースコード
66
+ 解決いたしました。mapに適当な初期値を入れて初期化しておくと上手くできました。
67
+ ```javaScript
68
+ //markerDataまでは同じです。
69
+
70
+ //この関数でmapを初期化しておきます。
71
+ //Google Maps PlatformドキュメントのMaps JavaScript API/Geocodingに掲載されているものです。
72
+
73
+ function initialize() {
74
+ geocoder = new google.maps.Geocoder();
75
+ var latlng = new google.maps.LatLng(-34.397, 150.644);
76
+ var mapOptions = {
77
+ zoom: 14,
78
+ center: latlng
79
+ }
80
+ map = new google.maps.Map(document.getElementById('map'), mapOptions);
81
+ }
82
+
83
+ function initMap() {
84
+
85
+ initialize();//マップの初期化
86
+
87
+ for (let i = 0; i < markerData.length; i++) {//ピンを多数立てるためにリストの数だけ回す
88
+ geocoder.geocode({
89
+ "address" : markerData[i].address
90
+ }, function(results, status) { // 結果
91
+ if (status === google.maps.GeocoderStatus.OK) { // ステータスがOKの場合
92
+ let bounds = new google.maps.LatLngBounds();
93
+ latlng = results[0].geometry.location;
94
+ bounds.extend(latlng);
95
+
96
+ //簡易的にしていますが本来はマップの中心に持ってきたい座標でのみmap.setCenter(latlng);をするべきだと思います。
97
+ if(i === 0){
98
+ map.setCenter(latlng);
99
+ }
100
+
101
+ //マーカーを立てる
102
+ marker[i] = new google.maps.Marker({
103
+ position: latlng,
104
+ map: map
105
+ });
106
+
107
+ } else { // 失敗した場合
108
+ console.group('Error');
109
+ console.log(results);
110
+ console.log(status);
111
+ }
112
+
113
+ });
114
+ }
115
+ }
63
116
  ```

1

ソースコード最後の}が抜けていたので付け足しました。

2019/12/15 02:43

投稿

masahirori
masahirori

スコア5

title CHANGED
File without changes
body CHANGED
@@ -59,4 +59,5 @@
59
59
  }
60
60
  });
61
61
  }
62
+ }
62
63
  ```