每当googlemaps视口中心发生变化时,我都会尝试使用邮政编码向我的数据库提交查询。我知道这可以通过反向地理编码完成,例如:
google.maps.event.addListener(map, 'center_changed', function(){
newCenter();
});
...
function newCenter(){
var newc = map.getCenter();
geocoder.geocode({'latLng': newc}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var newzip = results[0].address_components['postal_code'];
}
});
};
当然,这段代码实际上并不起作用。所以我想知道如何更改这个以便从结果数组中提取邮政编码。 感谢
答案 0 :(得分:17)
到目前为止我已经意识到在大多数情况下 ZIPCODE 总是每个返回地址中的最后一个值,所以,如果你想要检索它第一个zipcode(这是我的情况),您可以使用以下方法:
var address = results[0].address_components;
var zipcode = address[address.length - 1].long_name;
答案 1 :(得分:11)
使用JQuery?
var searchAddressComponents = results[0].address_components,
searchPostalCode="";
$.each(searchAddressComponents, function(){
if(this.types[0]=="postal_code"){
searchPostalCode=this.short_name;
}
});
short_name或long_name将在上面工作 “searchPostalCode”var将包含邮政(zip?)代码IF 并且只有从Google Maps API获得一个 有时你不会得到“postal_code”来换取你的查询。
答案 2 :(得分:10)
您可以使用underscore.js库轻松完成此操作:http://documentcloud.github.com/underscore/#find
_.find(results[0].address_components, function (ac) { return ac.types[0] == 'postal_code' }).short_name
答案 3 :(得分:10)
好吧,所以我明白了。解决方案比我想要的更加丑陋,我可能不需要最后一个for循环,但这里是需要从address_components []中提取废话的其他人的代码。这是在地理编码器回调函数
中for(i; i < results.length; i++){
for(var j=0;j < results[i].address_components.length; j++){
for(var k=0; k < results[i].address_components[j].types.length; k++){
if(results[i].address_components[j].types[k] == "postal_code"){
zipcode = results[i].address_components[j].short_name;
}
}
}
}
答案 4 :(得分:2)
这只需要两个for循环。一旦我们发现第一个“类型”为“postal_code”,“results”数组就会更新。
然后用新发现的数组设置更新原始数组并再次循环。
var i, j,
result, types;
// Loop through the Geocoder result set. Note that the results
// array will change as this loop can self iterate.
for (i = 0; i < results.length; i++) {
result = results[i];
types = result.types;
for (j = 0; j < types.length; j++) {
if (types[j] === 'postal_code') {
// If we haven't found the "long_name" property,
// then we need to take this object and iterate through
// it again by setting it to our master loops array and
// setting the index to -1
if (result.long_name === undefined) {
results = result.address_components;
i = -1;
}
// We've found it!
else {
postcode = result.long_name;
}
break;
}
}
}
答案 5 :(得分:2)
$.each(results[0].address_components,function(index,value){
if(value.types[0] === "postal_code"){
$('#postal_code').val(value.long_name);
}
});
答案 6 :(得分:2)
您也可以使用此代码,此功能有助于在按钮点击或onblur或keyup或keydown上获取zip。
只需将地址传递给此功能。
使用谷歌api删除有效的密钥和传感器选项,因为它现在不需要。
$(document).ready(function() {
var number = parseInt($('#director-uploads1').data('number'));
function clone(){
var director = $('.director-uploads-hidden').clone(true); //true will cause it to clone all associated data and events as well
director.data("number", number+1);
director.removeClass("director-uploads-hidden");
director.css("display", "block");
//if you want to add any other extra data or events, do it here before appending the object
$('#director-uploads1').append(director);
number++;
}
$("button#add-director").on("click", clone);
});
答案 7 :(得分:1)
您还可以使用JavaScript .find
方法,该方法类似于下划线_.find
方法,但是它是本机的,不需要任何额外的依赖关系。
const zip_code = results[0].address_components.find(addr => addr.types[0] === "postal_code").short_name;
答案 8 :(得分:1)
places.getDetails( request_details, function(results_details, status){
// Check if the Service is OK
if (status == google.maps.places.PlacesServiceStatus.OK) {
places_postal = results_details.address_components
places_phone = results_details.formatted_phone_number
places_phone_int = results_details.international_phone_number
places_format_address = results_details.formatted_address
places_google_url = results_details.url
places_website = results_details.website
places_rating = results_details.rating
for (var i = 0; i < places_postal.length; i++ ) {
if (places_postal[i].types == "postal_code"){
console.log(places_postal[i].long_name)
}
}
}
});
这对我来说似乎非常有效,这与新的Google Maps API V3有关。如果这有助于任何人,请写评论,我正在编写我的脚本,因为它们可能会改变。
答案 9 :(得分:1)
我使用此代码获取&#34;邮政编码&#34;和&#34; locality&#34;,但您可以使用它来获取任何其他字段只是更改类型的值:
<强> JAVASCRIPT 强>
var address = results[0].address_components;
var zipcode = '';
var locality = '';
for (var i = 0; i < address.length; i++) {
if (address[i].types.includes("postal_code")){ zipcode = address[i].short_name; }
if (address[i].types.includes("locality")){ locality = address[i].short_name; }
}
答案 10 :(得分:1)
在PHP中我使用此代码。几乎在每种情况下它都有效。
$zip = $data["results"][3]["address_components"];
$zip = $index[0]["short_name"];
答案 11 :(得分:0)
使用JSONPath,可以通过一行代码轻松完成:
var zip = $.results[0].address_components[?(@.types=="postal_code")].long_name;
答案 12 :(得分:0)
我知道zip是最后一个,或者是最后一个。 那就是为什么这是我的解决方法
const getZip = function (arr) {
return (arr[arr.length - 1].types[0] === 'postal_code') ? arr[arr.length - 1].long_name : arr[arr.length - 2].long_name;
};
const zip = getZip(place.address_components);
答案 13 :(得分:0)
我认为与其检查索引,不如更好地检查组件内部的地址类型键。我通过使用开关盒解决了这个问题。
var address = '';
var pin = '';
var country = '';
var state = '';
var city = '';
var streetNumber = '';
var route ='';
var place = autocomplete.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
var component = place.address_components[i];
var addressType = component.types[0];
switch (addressType) {
case 'street_number':
streetNumber = component.long_name;
break;
case 'route':
route = component.short_name;
break;
case 'locality':
city = component.long_name;
break;
case 'administrative_area_level_1':
state = component.long_name;
break;
case 'postal_code':
pin = component.long_name;
break;
case 'country':
country = component.long_name;
break;
}
}
答案 14 :(得分:0)
Romaine M. - 谢谢!如果您只需要在Google首次返回的结果中找到邮政编码,则只需执行2次循环:
for(var j=0;j < results[0].address_components.length; j++){
for(var k=0; k < results[0].address_components[j].types.length; k++){
if(results[0].address_components[j].types[k] == "postal_code"){
zipcode = results[0].address_components[j].long_name;
}
}
}
答案 15 :(得分:0)
现在似乎最好从宁静的API中获取它,只需尝试:
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_KEY_HERE
使用AJAX GET调用非常有效!
类似的东西:
var your_api_key = "***";
var f_center_lat = 40.714224;
var f_center_lon = -73.961452;
$.ajax({ url: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+f_center_lat+","+f_center_lon+"&key="+your_api_key,
method: "GET"
})
.done(function( res ) { if (debug) console.log("Ajax result:"); console.log(res);
var zipCode = null;
var addressComponent = res.results[0].address_components;
for (var x = 0 ; x < addressComponent.length; x++) {
var chk = addressComponent[x];
if (chk.types[0] == 'postal_code') {
zipCode = chk.long_name;
}
}
if (zipCode) {
//alert(zipCode);
$(current_map_form + " #postalcode").val(zipCode);
}
else {
//alert('No result found!!');
if (debug) console.log("Zip/postal code not found for this map location.")
}
})
.fail(function( jqXHR, textStatus ) {
console.log( "Request failed (get postal code via geocoder rest api). Msg: " + textStatus );
});
答案 16 :(得分:0)
//autocomplete is the text box where u will get the suggestions for an address.
autocomplete.addListener('place_changed', function () {
//Place will get the selected place geocode and returns with the address
//and marker information.
var place = autocomplete.getPlace();
//To select just the zip code of complete address from marker, below loop //will help to find. Instead of y.long_name you can also use y.short_name.
var zipCode = null;
for (var x = 0 ; x < place.address_components.length; x++) {
var y = place.address_components[x];
if (y.types[0] == 'postal_code') {
zipCode = y.long_name;
}
}
});
答案 17 :(得分:0)
return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val,
sensor: false
}
}).then(function (response) {
var model= response.data.results.map(function (item) {
// return item.address_components[0].short_name;
var short_name;
var st= $.each(item.address_components, function (value, key) {
if (key.types[0] == "postal_code") {
short_name= key.short_name;
}
});
return short_name;
});
return model;
});
答案 18 :(得分:0)
使用Jquery
var postalObject = $.grep(results[0].address_components, function(n, i) {
if (n.types[0] == "postal_code") {
return n;
} else {
return null;
}
});
$scope.query.Pincode = postalObject[0].long_name;
答案 19 :(得分:0)
这个简单的代码适合我
for (var i = 0; i < address.length; i++) {
alert(address[i].types);
if (address[i].types == "postal_code")
$('#postalCode').val(address[i].long_name);
if (address[i].types == "")
$('#country').val(address[i].short_name);
}
答案 20 :(得分:0)
总之,这是一项很大的努力。至少使用v2 API,我可以检索这些细节:
var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
myAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName
myCity = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName
myState = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName
myZipCode = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber
必须有一种更优雅的方式来检索单个address_components,而无需通过刚刚经历的循环jujitsu。