0

I want my vistior to enter a city name then I can get the latitude and longitude from that name. I could not figure out how to get them using google map api. I found world weather online api easy, so I have this json response but cannot walk through it.

{ "search_api" : {
    "result" : [
      { "areaName"   : [ { "value" : "New York" } ], 
        "country"    : [ { "value" : "United States Of America" } ],
        "latitude"   : "40.710",
        "longitude"  : "-74.010", 
        "population" : "8107916",  
        "region"     : [ { "value" : "New York" } ], 
        "weatherUrl" : [ { "value": "http:\/\/free.worldweatheronline.com\/weather\/United-States-Of-America\/2395340\/New-York\/2478232\/info.aspx" } ]
      }, 
      { "areaName"   : [ { "value" : "New York" } ],
        "country"    : [ { "value" : "United States Of America" } ],
        "latitude"   : "32.170",
        "longitude"  : "-95.670",
        "population" : "0",
        "region"     : [ { "value" : "Texas" } ],
        "weatherUrl" : [ { "value": "http:\/\/free.worldweatheronline.com\/weather\/United-States-Of-America\/2395340\/New-York\/2516758\/info.aspx" } ]
      }
    ]
  }
}

This is what I tried:

$.getJSON(url, function(data) {
  var cord = data.search_api.latitude;

  alert(cord);
} );

Can anybody help me out with this or give me a better way to get longitude and latitude from a given city name or address?

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Timmy
  • 107
  • 4
  • 18

1 Answers1

0

Your code doesn't work because you try to jump straight from search_api to latitude when you need to go through the array named result first, e.g.

$.getJSON( url, function( data ) {
  var firstResult = data.search_api.result[ 0 ];

  console.log( "City:",      firstResult.areaName[ 0 ].value, ",",
                             firstResult.region[ 0 ].value
  );
  console.log( "Latitude:",  firstResult.latitude );
  console.log( "Longitude:", firstResult.longitude );
} );

/* Output:
   > City: New York , New York
   > Latitude: 40.710
   > Longitude: -74.010
*/
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • That's too bad, but "didn't work" doesn't mean anything to us. What error did you get or what result did you get that you didn't expect? What is the value of `data`? – Jordan Running Feb 27 '12 at 01:48
  • I want to show the Latitude and Longitude as you did here, but it gives me this "Uncaught SyntaxError: Unexpected token :" – Timmy Feb 27 '12 at 01:58
  • Debug it like you would any syntax error. What line in the code does it refer to? There's no syntax error in the code I posted so it's either in the JSON data (are you sure it's plain JSON?) or somewhere else in your code. – Jordan Running Feb 27 '12 at 15:56