javascript - Parsing city/state from Google Maps request -
var geocoder = new google.maps.geocoder(); geocoder.geocode({'latlng': foundloc}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { if (results[1]) { var loc = getcitystate(results); } } }); function getcitystate(results) { var citystatearray = results[1].formatted_address.split(",",2); var city = citystatearray[0]; var state = citystatearray[1].substring(1, 3); return (city + ', ' + state) }
this use now, , works 90% of time. other times, formatted_address
contains town , city along state, other times town , city, other times can dream of.
i haven't yet found consistent way of getting city/state google maps api result. of guys have one? thanks.
example of 1 response google uses example on page:
{ "status": "ok", "results": [ { "types": [ "street_address" ], "formatted_address": "1600 amphitheatre pkwy, mountain view, ca 94043, usa", "address_components": [ { "long_name": "1600", "short_name": "1600", "types": [ "street_number" ] }, { "long_name": "amphitheatre pkwy", "short_name": "amphitheatre pkwy", "types": [ "route" ] }, { "long_name": "mountain view", "short_name": "mountain view", "types": [ "locality", "political" ] }, { "long_name": "california", "short_name": "ca", "types": [ "administrative_area_level_1", "political" ] }, { "long_name": "united states", "short_name": "us", "types": [ "country", "political" ] }, { "long_name": "94043", "short_name": "94043", "types": [ "postal_code" ] } ], "geometry": { "location": { "lat": 37.4219720, "lng": -122.0841430 }, "location_type": "rooftop", "viewport": { "southwest": { "lat": 37.4188244, "lng": -122.0872906 }, "northeast": { "lat": 37.4251196, "lng": -122.0809954 } } } } ] }
sometimes fields don't have values, do.
why parse formatted_address
?
there address_components, can walk through them , ones
"types": [ "administrative_area_level_1", "political" ]// state "types" : [ "locality", "political" ]//the city
here's example: http://jsfiddle.net/doktormolle/qwpcl/
Comments
Post a Comment