gpt4 book ai didi

javascript - 从谷歌地图中获取第一个地址段

转载 作者:行者123 更新时间:2023-11-28 09:20:52 24 4
gpt4 key购买 nike

理想情况下,使用 Google API 而不是 Javascript hack 来获取逗号之前的所有内容,我想知道是否可以获取框中地址的第一位。这是我正在使用的代码:

http://jsfiddle.net/Xw4ZM/3/

var geocoder;
var map;
var marker;

function initialize(){
//MAP
var latlng = new google.maps.LatLng(41.659,-4.714);
var options = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};

map = new google.maps.Map(document.getElementById("map_canvas"), options);

//GEOCODER
geocoder = new google.maps.Geocoder();

marker = new google.maps.Marker({
map: map,
draggable: true
});

}

$(document).ready(function() {

initialize();

$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#latitude").val(ui.item.latitude);
$("#longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});

//Add listener to marker for reverse geocoding
google.maps.event.addListener(marker, 'drag', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
}
});
});

});

这是我想要实现的场景,如果用户输入:

Swindon, Wiltshire, United Kingdom
The "name" value is this: "Swindon"

Wiltshire, United Kingdom:
The "name" value is this "Wiltshire"

United Kingdom:
The "name" value is this "United Kingdom"

它基本上保存了名称字段中提供的最准确的位置,无论是城镇、城市、县还是国家。

最佳答案

不确定它是否可以帮助您解决您的情况,但地址搜索结果对象中有地址组件。

https://developers.google.com/maps/documentation/geocoding/#JSON

geocoder.geocode({
'address': request.term
}, function (results, status) {
for (i in results) {
var result = results[i];

for (j in result.address_components) {
var segment = result.address_components[j];

// do something with address segment
}
}
})

geocoder.geocode({
'address': request.term
}, function (results, status) {
$.each(results, function (i, result) {
$.each(result.address_components, function (i, segment) {
// do something with address segment
});
});
})

关于javascript - 从谷歌地图中获取第一个地址段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15002732/

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