Javascript 谷歌地图地理编码器如何在新的Google.maps.LatLng中返回值?
我有以下代码: 函数getLatLong(地址){ var geocoder=new google.maps.geocoder(); var结果=”; geocoder.geocode({'address':address},函数(结果,状态){ if(status==google.maps.GeocoderStatus.OK){ 结果[lat]=结果[0]。geometry.location.Pa; 结果[lng]=结果[0]。geometry.location.Qa; }否则{ 结果=“找不到地址:”+状态; } 存储结果(result); }); } directionsDisplay=new google.maps.DirectionsRenderer(); var directionsService=new google.maps.directionsService(); var请求={ 来源:新的google.maps.LatLng(getLatLong()[0],getLatLong()[1]), 目的地:新google.maps.LatLng(59.79530896374892,30.410317182540894), travelMode:google.maps.Directions travelMode.DRIVING/ }; 路由(请求、功能(响应、状态){ if(status==google.maps.directionstatus.OK){ 方向显示。设置方向(响应); } }); map=新的google.maps.map(document.getElementById(“map”);Javascript 谷歌地图地理编码器如何在新的Google.maps.LatLng中返回值?,javascript,google-maps,Javascript,Google Maps,我有以下代码: 函数getLatLong(地址){ var geocoder=new google.maps.geocoder(); var结果=”; geocoder.geocode({'address':address},函数(结果,状态){ if(status==google.maps.GeocoderStatus.OK){ 结果[lat]=结果[0]。geometry.location.Pa; 结果[lng]=结果[0]。geometry.location.Qa; }否则{ 结果=“找
方向显示.setMap(地图)代码>地理编码器是异步的,您不能从回调函数返回值,您需要在可用的时间/地点(在回调函数中)使用它们
- 参考:
function getLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var request = {
origin: results[0].geometry.location,
destination: new google.maps.LatLng(59.79530896374892, 30.410317182540894),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert("directions failed:" + status)
}
});
} else {
result = "Unable to find address: " + status;
}
});
}
代码片段:
var地理编码器;
var映射;
var方向显示;
var定向服务;
函数初始化(){
map=新建google.maps.map(
document.getElementById(“map”){
中心:新google.maps.LatLng(37.4419,-122.1419),
缩放:13,
mapTypeId:google.maps.mapTypeId.ROADMAP
});
directionsDisplay=new google.maps.DirectionsRenderer();
directionsService=new google.maps.directionsService();
map=新的google.maps.map(document.getElementById(“map”);
方向显示.setMap(地图);
getLatLong(“俄罗斯圣彼得堡”);
}
google.maps.event.addDomListener(窗口“加载”,初始化);
函数getLatLong(地址){
var geocoder=new google.maps.geocoder();
地理编码({
“地址”:地址
},功能(结果、状态){
if(status==google.maps.GeocoderStatus.OK){
var请求={
原点:结果[0]。geometry.location,
目的地:新google.maps.LatLng(59.79530896374892,30.410317182540894),
travelMode:google.maps.Directions travelMode.DRIVING
};
路由(请求、功能(响应、状态){
if(status==google.maps.directionstatus.OK){
方向显示。设置方向(响应);
}否则{
警报(“指示失败:+状态”)
}
});
}否则{
结果=“找不到地址:”+状态;
}
});
}
html,
身体,
#地图{
身高:100%;
宽度:100%;
边际:0px;
填充:0px
}
location.Pa
,location.Qa
不是稳定的变量名,它们是由闭包编译器生成的,并且可以并且确实随API的每个版本而更改。我如何处理2个地址?原点:结果[0]。几何体。位置,目标:结果[1]。几何体。位置?