グーグルマップに複数個所ピンを立てて、クリックしたらピンがたった場所への説明がポップアップで出てくるプログラムを作りたいのです。しかし上手く行かなくて困っています。
こんな感じのプログラムの流れにしたいです。
1 DBから住所データをPHPで取得してスクリプトタグ内でループさせる
2 住所をgeocoder内で展開させて緯度と経度を取得する
3 取得した緯度、経度を配列に入れて配列に入れる
4 google.maps.LatLngに緯度、経度と表示したいコンテンツを入れたオブジェクトを住所分生成する
5 new google.maps.Markerとクリックを監視するattachMessageを生成したオブジェクト分呼ぶ
という流れにしたいのですが、2を実行すると、コールバック関数の中から自分がやると値を持ち出せなくて、3以降する事ができません。
2と3の部分のコード
lang
1 2 <?php 3 $address = array( 4 "愛知県名古屋市西区浄心", 5 "愛知県名古屋市中村区名駅南", 6 "愛知県名古屋市中村区亀島", 7 "愛知県名古屋市中村区東区白壁", 8 "愛知県名古屋市中区栄4丁目", 9 "愛知県名古屋市中区栄1丁目", 10 "愛知県名古屋市中川区山王1丁目", 11 "愛知県名古屋市中区丸の内", 12 ); 13 ?> 14 15 var data = new Array(); 16 17 18 <?php for($i=0; $i<count($address); $i++) : ?> 19 20 var geocoder = new google.maps.Geocoder(); 21 geocoder.geocode( 22 { address: '<?php echo $address[$i]; ?>' }, 23 function( results, status ) 24 { 25 if( status == google.maps.GeocoderStatus.OK ) 26 { 27 lat = results[0].geometry.location.k; 28 lng = results[0].geometry.location.D; 29 data.push({position: new google.maps.LatLng(lat,lng), content: '物件<?php echo $i; ?>'}) 30 31 /* コールバック関数の外で代入しようと思いましたができませんでした・・・ */ 32 geocoder.lat = results[0].geometry.location.k; 33 34 35 } 36 else 37 { 38 alert( 'Faild:' + status ); 39 } 40 } 41 ); 42 43 <?php endfor; ?> 44 45 console.log(data); //[] 46 console.log(geocoder); 47 /* 48 zi {geocode: function}lat: 35.1742916lng: 136.89973759999998__proto__: zi 49...(゚∀゚) 50 */ 51 console.log(geocoder.lat); //undefined 52 console.log(geocoder.zi) // undefined 53 54 //...orz 55
jsonデータをループさせました。間違えてたらごめんなさい。
lang
1 2 3 var data = new Array(); 4 var geocoder = new google.maps.Geocoder(); 5 var encode = 'db→PHP→jsonencodeしたデータ'; 6 var addressAr = JSON.parse(encode); 7 8 for(i=0; i<addressAr.length; i++) 9 { 10 11 12 geocoder.geocode( 13 { address: addressAr[i] }, 14 function( results, status ) 15 { 16 if( status == google.maps.GeocoderStatus.OK ) 17 { 18 lat = results[0].geometry.location.k; 19 lng = results[0].geometry.location.D; 20 console.log(lat,lng); 21 /* 22 35.1927384 136.88722489999998 23 (index):96 35.1589488 136.8899139 24 (index):96 35.1754295 136.8752482 25 (index):96 35.1687471 136.87301509999998 26 (index):96 35.1676346 136.91235329999995 27 (index):96 35.1671924 136.89628530000005 28 (index):96 35.1536495 136.89023900000007 29 (index):96 35.1742916 136.89973759999998 30 */ 31 data.push({position: new google.maps.LatLng(lat,lng), content: 'ab'}) 32 /*dataのデータが増えない*/ 33 } 34 else 35 { 36 alert( 'Faild:' + status ); 37 } 38 } 39 ); 40 } 41 42 console.log(data.length); // 0 43 44 for (i = 0; i < data.length; i++) { 45 var myMarker = new google.maps.Marker({ 46 position: data[i].position, 47 map: mapdiv 48 }); 49 attachMessage(myMarker, data[i].content); 50// google.maps.InfoWindowを呼ぶプログラム 51 } 52 53
ぶしつけですみません。もし分かる方が居たら、助言を下さい・・・。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/03/30 06:56