使用 JS 函数对结果进行地理编码 - 地址拆分



我对地理编码器功能有问题。 这是我的JS函数:

function init_map() {
searchLanLon();
var latitudine = document.getElementById('lat').value;
var longitudine = document.getElementById('lng').value;
var myLatLng = new google.maps.LatLng(latitudine, longitudine);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'location': myLatLng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var options = {
zoom: 15,
center: myLatLng,
mapeTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker({ position: myLatLng, map: map, draggable: true });
google.maps.event.addListener(marker, "dragend", function () {
document.getElementById('address').value = results[0].formatted_address;
});
document.getElementById('address').value = results[0].formatted_address;
} else {
alert("Problema nella ricerca : " + status);
}
});
}
window.onload = init_map;

该函数有效,但我需要一个分为街道、号码、城市、邮政编码的地址,以便将其保存在具有此字段的数据库中。

如何拆分地址? 谢谢

查看地理编码文档 https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses

您正在使用formatted_address但您address_components中的每个结果都有更多信息

{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}

最新更新