理想情况下,使用Google API而不是Javascript hack来获取逗号前的所有内容,我想知道是否可以在一个框中抓取地址的第一位。这是我正在使用的代码:
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"
它基本上保存了名称字段中提供的最准确的位置,无论是城镇,城市,县还是国家。
答案 0 :(得分:0)
不确定它是否可以帮助您,但地址搜索结果对象中有地址组件。
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
});
});
})