作者ww410490 (致命伸卡球)
看板Ajax
标题[问题] google map api 与函数传值
时间Mon May 12 13:36:57 2014
各位前辈大大好
小弟练习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>
-------------------------------------------------------------
程式码中,用变数 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://webptt.com/cn.aspx?n=bbs/Ajax/M.1399873019.A.527.html
1F:推 KawasumiMai:你的name是区域变数吧?在function外面宣告一下 05/12 20:07
2F:→ ww410490:可是name前面并没有var,应该属於全域变数吧 05/12 22:19
3F:推 shaopin:你用name的时间点 早於name得到地址的时间点, name 就无值 05/14 00:14
4F:→ ww410490:愿闻其详 该如何改呢 05/14 01:02
5F:推 shaopin:one option is to use callback, in the callback, 'name' 05/14 10:31
6F:→ shaopin:most likely is guarnteed to have value 05/14 10:31
7F:→ shaopin:function initialize(callback) {...} 05/14 10:32
8F:→ shaopin:sorry it should be codeLatLng(a, b, cb){...} 05/14 10:33
9F:推 shaopin:and in your call to google api, it is asynchrounous 05/14 10:45
10F:→ ww410490:楼上太神啦! callback太神啦! 05/14 12:30