javascript - 使用 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"
}
推荐阅读
- c# - 使用动态 IP 进行套接字编程
- javascript - 在 JS 中为元素添加数据属性
- matplotlib - matplotlib 中的网格
- python - python.clang AST 解析:获取字段声明的 c++ 模板参数
- apache-spark - 使用 spark 将 parquet 数据从 Google 云存储加载到 BigQuery
- jquery - jquery函数只执行一次
- javascript - 解决 VueJs 和 IE11 中的 Promise
- reactjs - 修改 react-native-progress-steps npm 库部分
- php - 如何在 Eloquent ORM Laravel 中保留“created_at”的同时删除“updated_at”
- algorithm - 如何解决 3×3 网格中的黑白骑士问题