Having problems getting the different arrays content from geocoder results.
item.formatted_address works but not item.address_components.locality?
ge
// Use Google Geocoder to get Lat/Lon for Address
function codeAddress() {
// Function geocodes address1 in the Edit Panel and fills in lat and lon
address = document.getElementById("tbAddress").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc[0] = results[0].geometry.location.lat();
loc[1] = results[0].geometry.location.lng();
document.getElementById("tbLat").value = loc[0];
document.getElementById("tbLon").value = loc[1];
var arrAddress = results[0].address_components;
for (ac = 0; ac < arrAddress.length; ac++) {
if (arrAddress[ac].types[0] == "street_number") { document.getElementById("tbUnit").value = arrAddress[ac].long_name }
if (arrAddress[ac].types[0] == "route") { document.getElementById("tbStreet").value = arrAddress[ac].short_name }
if (arrAddress[ac].types[0] == "locality") { document.getElementById("tbCity").value = arrAddress[ac].long_name }
if (arrAddress[ac].types[0] == "administrative_area_level_1") { document.getElementById("tbState").value = arrAddress[ac].short_name }
if (arrAddress[ac].types[0] == "postal_code") { document.getElementById("tbZip").value = arrAddress[ac].long_name }
}
document.getElementById("tbAddress").value = results[0].formatted_address;
}
document.getElementById("pResult").innerHTML = 'GeoCode Status:' + status;
})
}
I had to create a program that would fill in the latitude, longitude, city, county, and state fields in a user form when the user clicks on a location on the map. The page can be found at http://krcproject.groups.et.byu.net and is a user form to allow the public to contribute to a database. I don't claim to be an expert, but it works great.
<script type="text/javascript">
function initialize()
{
//set initial settings for the map here
var mapOptions =
{
//set center of map as center for the contiguous US
center: new google.maps.LatLng(39.828, -98.5795),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
//load the map
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
//This runs when the user clicks on the map
google.maps.event.addListener(map, 'click', function(event)
{
//initialize geocoder
var geocoder = new google.maps.Geocoder()
//load coordinates into the user form
main_form.latitude.value = event.latLng.lat();
main_form.longitude.value = event.latLng.lng();
//prepare latitude and longitude
var latlng = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
//get address info such as city and state from lat and long
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//break down the three dimensional array into simpler arrays
for (i = 0 ; i < results.length ; ++i)
{
var super_var1 = results[i].address_components;
for (j = 0 ; j < super_var1.length ; ++j)
{
var super_var2 = super_var1[j].types;
for (k = 0 ; k < super_var2.length ; ++k)
{
//find city
if (super_var2[k] == "locality")
{
//put the city name in the form
main_form.city.value = super_var1[j].long_name;
}
//find county
if (super_var2[k] == "administrative_area_level_2")
{
//put the county name in the form
main_form.county.value = super_var1[j].long_name;
}
//find State
if (super_var2[k] == "administrative_area_level_1")
{
//put the state abbreviation in the form
main_form.state.value = super_var1[j].short_name;
}
}
}
}
}
});
});
}
</script>
Returns locality if exist. If not - returns administrative_area_1
city = results[0].address_components.filter(function(addr){
return (addr.types[0]=='locality')?1:(addr.types[0]=='administrative_area_level_1')?1:0;
});
I used a lodash function called find which returns the object that the predicate returns true for. As simple as that!
let city = find(result, (address) => {
return typeof find(address.types, (a) => { return a === 'locality'; }) === 'string';
});
Well this worked for me if you want to get the city
var city = "";
function getPositionByLatLang(lat, lng) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//formatted address
city = results[0].plus_code.compound_code;
city = city.substr(0, city.indexOf(','));
city = city.split(' ')[1];
console.log("the name of city is: "+ city);
}
} else {
// alert("Geocoder failed due to: " + status);
}
});
}
tried a couple of different requests:
MK107BX
Cleveland Park Crescent, UK
like you say, array size returned is inconsistent but the Town for both results appears to be in the address_component item with type of [ "locality", "political" ]. Perhaps you could use that as an indicator?
EDIT: get the locality object using jQuery, add this to your response function:
var arrAddress = item.results[0].address_components;
// iterate through address_component array
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "locality") // locality type
console.log(address_component.long_name); // here's your town name
return false; // break the loop
});