Javascript 谷歌地图地理编码不返回位置
我试图在javascript中使用谷歌地图地理编码API。我有以下代码:Javascript 谷歌地图地理编码不返回位置,javascript,google-maps,geocoding,google-geocoding-api,Javascript,Google Maps,Geocoding,Google Geocoding Api,我试图在javascript中使用谷歌地图地理编码API。我有以下代码: var geocoder = new google.maps.Geocoder(); function geocodeAddress() { var address = document.getElementById("address").value; geocoder.geocode({"address": address}, function(results, status) { if (status
var geocoder = new google.maps.Geocoder();
function geocodeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode({"address": address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
alert(JSON.stringify(results[0].geometry))
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
我得到的正确地址的结果是:
{"location":{},"location_type":"ROOFTOP","viewport":{"O":{"O":52.2080810197085,"j":52.2107789802915},"j":{"j":21.018444019708568,"O":21.02114198029153}}}
正如您所看到的,它没有正确设置位置。有什么问题吗?
Location
属性属于google.maps.LatLng
对象类型,这反过来需要显式转换为打印lat/lng值,例如:
var sval = results[0].geometry.location.toString();
或者,您可以使用相应的功能访问lat/lng值:
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
要打印位置
属性的字符串表示形式,可以替换:
alert(JSON.stringify(results[0].geometry));
与
在哪里
现场示例
var地理编码器;
var映射;
函数初始化(){
geocoder=新的google.maps.geocoder();
var latlng=新的google.maps.latlng(-34.397150.644);
变量映射选项={
缩放:8,
中心:拉丁
}
map=new google.maps.map(document.getElementById('map-canvas'),mapOptions);
}
函数代码地址(){
var address=document.getElementById('address')。值;
geocoder.geocode({'address':address},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
var json=json.stringify(结果[0].geometry,convertLatLngValue,4);
document.getElementById('output').innerHTML=json;
map.setCenter(结果[0].geometry.location);
var marker=new google.maps.marker({
地图:地图,
位置:结果[0]。几何体。位置
});
}否则{
警报('地理编码因以下原因未成功:'+状态);
}
});
}
函数转换器LNGVALUE(键,值)
{
如果(键==“lat”| |键==“lng”){
返回值();
}
其他的
返回值;
}
google.maps.event.addDomListener(窗口“加载”,初始化)代码>
html,主体,#地图画布{
高度:240px;
边际:0px;
填充:0px;
}
#面板{
位置:绝对位置;
顶部:5px;
左:50%;
左边距:-180px;
z指数:5;
背景色:#fff;
填充物:5px;
边框:1px实心#999;
}
您将使用坐标做什么?您可以使用文档化的.lat()
和.lng()
方法从google.maps.LatLng对象中获取它们。
alert(JSON.stringify(results[0].geometry,convertLatLngValue,4));
function convertLatLngValue(key,value)
{
if (key=="lat" || key=="lng") {
return value();
}
else
return value;
}