Search code examples
javascriptgoogle-maps-api-3

Get LatLng from Zip Code - Google Maps API


All I want is some simple example code that shows me how to obtain a latlng element from an inputted zip code OR a city/state.


Solution

  • Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}

    Google Geocoding

    Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)

    EXAMPLE to get lat/lng:

        var lat = '';
        var lng = '';
        var address = {zipcode} or {city and state};
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
             lat = results[0].geometry.location.lat();
             lng = results[0].geometry.location.lng();
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
        alert('Latitude: ' + lat + ' Logitude: ' + lng);