1

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?

3
  • 2
    possible duplicate of How to search JSON tree with jQuery Commented Dec 23, 2013 at 4:48
  • check if the current selected object has an array that contains the string "locality or administrative_area_level_1".. Commented Dec 23, 2013 at 4:49
  • @AkshayKhandelwal, how do I do that? Commented Dec 23, 2013 at 4:53

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Off course you send the array to be parsed for the value. Hence if you r return value is inside a data object like var data = {} and you save the return value as data = {"address_components" : [{...}]} then you pass the data["address_components"].getById..
2

Instead of polluting your code, you can use this JS lib; DefiantJS (http://defiantjs.com) which extends the global object JSON with the method "search". This method enables you to search a JSON structure with XPath query syntax. The result is that your code becomes much cleaner and readable.

Here is the working fiddle;
http://jsfiddle.net/hbi99/SjvZ9/

var data = {
       ...
    },
    res = JSON.search( data, '//*[types="administrative_area_level_1" or types="locality"]' ),
    str = '';

    for (var i=0; i<res.length; i++) {
        str += res[i].long_name +'<br/>';
    }

    document.getElementById('output').innerHTML = str;

Not familiar with XPath? Check out this XPath Evaluator to give you a hint of how easy it is; http://www.defiantjs.com/#xpath_evaluator

Comments

1

Try this:

var data = {"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" ]
        }
]};
for(var i = 0; i < data.address_components.length; i++){
    if(data[i].long_name == 'something'){
      // do something
    }
    //or
    if(data[i].types[0] == 'administrative_area_level_1'){
      // do something
    }
}

Comments

1

Try this,

var addr_comp = [{"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"]}];
function getlocalityAdminLevel(addrType){
    for(var a=0,len=addr_comp.length;a<len;a++){
        ac=addr_comp[a];
        if(ac.types){
            for (var t = 0, tl = ac.types.length; t < tl; t++) {
                ty = ac.types[t];
                if (ty == addrType) {
                    return ac;break;
                } 
            }
        }
    }
}
console.log(getlocalityAdminLevel('locality'));
console.log(getlocalityAdminLevel('administrative_area_level_1'));

Working demo

You can get long_name and short_name by using it like,

locality=getlocalityAdminLevel('locality');
if(locality && locality.long_name){
    alert(locality.long_name);
}

Demo 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.