gpt4 book ai didi

javascript - 谷歌地图地理编码不返回位置

转载 作者:行者123 更新时间:2023-11-29 19:20:15 25 4
gpt4 key购买 nike

我正在尝试在 javascript 中使用 Google Maps Geocoding API。我有以下代码:

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();

或者您可以使用相应的函数访问经纬度值:

var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();

为了打印 Location 属性的字符串表示,您可以替换:

alert(JSON.stringify(results[0].geometry));

alert(JSON.stringify(results[0].geometry,convertLatLngValue,4));

在哪里

function convertLatLngValue(key,value)
{
if (key=="lat" || key=="lng") {
return value();
}
else
return value;
}

实例

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var json = JSON.stringify(results[0].geometry,convertLatLngValue,4);
document.getElementById('output').innerHTML = json;
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}


function convertLatLngValue(key,value)
{
if (key=="lat" || key=="lng") {
return value();
}
else
return value;
}

google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 240px;
margin: 0px;
padding: 0px;
}

#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
<pre id="output"></pre>

关于javascript - 谷歌地图地理编码不返回位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33379960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com