Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  42] [ 3]  / answers: 1 / hits: 27068  / 11 Years ago, mon, december 23, 2013, 12:00:00

I'm using Google Maps to return the location name and state of where the user's location is. This is the portion I'm interested in:



address_components : [
{
long_name : Salem,
short_name : Salem,
types : [ locality, political ]
},
{
long_name : Rockingham,
short_name : Rockingham,
types : [ administrative_area_level_2, political ]
},
{
long_name : New Hampshire,
short_name : NH,
types : [ administrative_area_level_1, political ]
},
{
long_name : United States,
short_name : US,
types : [ country, political ]
}
]


Is there a way to find which objects contain the locality and administrative_area_level_1 value and return the long_name string of the appropriate object using JavaScript or jQuery? How would I go about doing so?


More From » jquery

 Answers
26

There you go. Please find the fiddle here



By using a function like below:



function getLocality(){
for(var i = 0 ; i< address_components.length; i++){
var obj = address_components[i];
var arr = obj[types];
for(var j = 0; j<arr.length;j++ ){
if(arr[j] == locality){
return obj;
}
}

}
}


Or rather writing the Array prototype that does the same



Array.prototype.getByType = function(type){
for(var i = 0 ; i< address_components.length; i++){
var obj = address_components[i];
var arr = obj[types];
for(var j = 0; j<arr.length;j++ ){
if(arr[j] == type){
return obj;
}
}

}
}


And Using the Prototype as below:



address_components.getByType(administrative_area_level_1).long_name // Note that you pass the type to the prototype function that does the job for you


where address_components is the Array returned by the Google Maps


[#73590] Saturday, December 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alonso

Total Points: 747
Total Questions: 108
Total Answers: 105

Location: Mauritania
Member since Sun, Sep 25, 2022
2 Years ago
;