[問題] google map api 與函數傳值

看板Ajax作者 (致命伸卡球)時間10年前 (2014/05/12 13:36), 編輯推噓4(406)
留言10則, 3人參與, 最新討論串1/1
各位前輩大大好 小弟練習google map api, 手邊有一些經緯度資料, 想利用"reverse geocoding"的服務將經緯度轉換成地址 程式碼如下: <!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <script src="" rel="nofollow">https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <script> var map; var geocoder; var infowindow = new google.maps.InfoWindow(); var marker; var directionsDisplay; var directionsService = new google.maps.DirectionsService(); function initialize() { geocoder = new google.maps.Geocoder(); directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { zoom: 8, center: new google.maps.LatLng(-34.397, 150.644) }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); //directionsDisplay.setMap(map); //return map; codeLatLng("25.017918","121.53779830000008"); var x = codeLatLng("25.017918","121.53779830000008"); console.log(x); directionsDisplay.setMap(map); } function codeLatLng(a,b) { var latlng = new google.maps.LatLng(a, b); geocoder.geocode({'latLng': latlng}, function(results, status) { marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); name =(results[1].formatted_address); //得到地址名稱 console.log(name); return name; }); } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas"></div> </body> </html> ------------------------------------------------------------- 程式碼中,用變數 name 儲存得到的地址名稱, 但是我想要將name傳到codeLatLng(a,b)函數外面,讓我能繼續使用name, 於是在function initialize()裡面, var x = codeLatLng("25.017918","121.53779830000008"); console.log(x); 我想要用 x 當作name來使用。 地圖雖然有照著經緯度移動, 但是我卻無法在codeLatLng(a,b)以外的地方獲得name的正確值, console.log(x)只得到 "undefined "。正確的話應該得到"106台灣台北市大安區學府里 請教各位前輩高人,該如何調整code,才能得到正確的值? Any help is appreciated. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.166.9 ※ 文章網址: http://www.ptt.cc/bbs/Ajax/M.1399873019.A.527.html

05/12 20:07, , 1F
你的name是區域變數吧?在function外面宣告一下
05/12 20:07, 1F

05/12 22:19, , 2F
可是name前面並沒有var,應該屬於全域變數吧
05/12 22:19, 2F

05/14 00:14, , 3F
你用name的時間點 早於name得到地址的時間點, name 就無值
05/14 00:14, 3F

05/14 01:02, , 4F
願聞其詳 該如何改呢
05/14 01:02, 4F

05/14 10:31, , 5F
one option is to use callback, in the callback, 'name'
05/14 10:31, 5F

05/14 10:31, , 6F
most likely is guarnteed to have value
05/14 10:31, 6F

05/14 10:32, , 7F
function initialize(callback) {...}
05/14 10:32, 7F

05/14 10:33, , 8F
sorry it should be codeLatLng(a, b, cb){...}
05/14 10:33, 8F

05/14 10:45, , 9F
and in your call to google api, it is asynchrounous
05/14 10:45, 9F

05/14 12:30, , 10F
樓上太神啦! callback太神啦!
05/14 12:30, 10F
文章代碼(AID): #1JS5txKd (Ajax)