我对此非常陌生,想知道如何获取完整的字符串而不是当前正在进行的第一个字符,
目前正在使用https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
中的html + js示例function codeLatLng(callback) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(17);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
document.getElementById('Addressb').value= results[0].formatted_address; //working
document.getElementById('Strn').value = results[0].formatted_address[0];
document.getElementById('Strna').value = results[0].formatted_address[2];
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
结果需要存储在指定的文本字段中,如下所示
Street Number: <input id="Strn" type="text"><br>
Street Name: <input id="Strna" type="text"><br>
Suburb: <input id="Subu" type="text"><br>
Town: <input id="Town" type="text"><br>
Code: <input id="Code1" type="text"><br>
答案 0 :(得分:1)
你必须遍历地址组件,然后是类型,这里是代码
var streetNumber;
var streetName;
var city;
var state;
var zip;
var country;
for(var i = 0; i < results[0].address_components.length; i++){
for(var k = 0; k < results[0].address_components[i].types.length; k++){
if (results[0].address_components[i].types[k] == "street_number")
streetNumber = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "route")
streetName = results[0].address_components[i].short_name;
else if (results[0].address_components[i].types[k] == "locality")
city = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "administrative_area_level_1")
state = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "postal_code")
zip = results[0].address_components[i].long_name;
else if (results[0].address_components[i].types[k] == "country")
country = results[0].address_components[i].long_name;
}
}
答案 1 :(得分:0)
Here's a link Google地图地理编码文档,指定响应的格式。
它看起来确实按照特定的顺序在address_components
数组中单独返回地址的组件。因此,如果您要对街道地址进行地理编码,则address_components[0].long_name
应返回街道地址,address_components[1].long_name
街道名称等。
希望有所帮助。