我正在尝试在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}}}
正如您所看到的,它没有正确设置位置。有什么建议吗?
答案 0 :(得分:3)
Location
属性属于google.maps.LatLng
对象类型,后者又需要显式转换为print 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();
为了打印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>
&#13;