[问题] google map api 与函数传值

楼主: ww410490 (致命伸卡球)   2014-05-12 13:36:57
各位前辈大大好
小弟练习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="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>
作者: KawasumiMai (さあ、死ぬがいい)   2014-05-12 20:07:00
你的name是区域变量吧?在function外面宣告一下
楼主: ww410490 (致命伸卡球)   2014-05-12 22:19:00
可是name前面并没有var,应该属于全域变量吧
作者: shaopin (Brian)   2014-05-14 00:14:00
你用name的时间点 早于name得到地址的时间点, name 就无值
楼主: ww410490 (致命伸卡球)   2014-05-14 01:02:00
愿闻其详 该如何改呢
作者: shaopin (Brian)   2014-05-14 10:31:00
one option is to use callback, in the callback, 'name'most likely is guarnteed to have valuefunction initialize(callback) {...}sorry it should be codeLatLng(a, b, cb){...}and in your call to google api, it is asynchrounous
楼主: ww410490 (致命伸卡球)   2014-05-14 12:30:00
楼上太神啦! callback太神啦!

Links booklink

Contact Us: admin [ a t ] ucptt.com