62

I'm using the following geocoding function to convert a textual address into latitude and longitude numbers, but it's not working right. The alert writes "undefined".

Can anyone say what's wrong?

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.latitude;
    var longitude = results[0].geometry.location.longitude;
    alert(latitude);
    } 
}); 
</script>
Ash
  • 1,289
  • 3
  • 17
  • 24

4 Answers4

93

Try using this instead:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

It's bit hard to navigate Google's api but here is the relevant documentation.

One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.

$.each(results[0].address_components, function(){
    $("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});

What I'm doing is to loop through all the returned address_components and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components value.
If you're only interrested in the whole formated address then you can follow Google's example

Skadlig
  • 1,569
  • 1
  • 14
  • 16
54

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
  • @Damcrumb , can you help me about this question? http://stackoverflow.com/questions/17587352/geocode-does-not-determine-point-location-exactly-on-google-map – Jeyhun Rahimov Jul 11 '13 at 10:33
  • 2
    This is great code, but I've another question, what if I would need those values in the exectuion of my Javascript, and not only inside the parameter function inside the geocode call? Thanks – axel Sep 09 '15 at 13:43
  • The above code is missing the required API key and will not work – WebDude0482 Jun 21 '17 at 15:30
4

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "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" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

AllJs
  • 1,760
  • 4
  • 27
  • 48
  • How do you restrict ``YOUR_API_KEY`` to your site when doing XHR requests? We are facing the problem that we can't restrict our key to the appropriate referer, the API answers with something like "geocode api should use a server-key". Obviously we can implement this on the server-side and just proxy the request, but that seems just weird. Is there any way to geocode on the client side and restrict the api key? – Daniel G. Mar 14 '17 at 14:03
  • 1
    The only solution I can think of at the top of my head would be to store the `API_KEY` on the server as a variable and access it via an `AJAX` call on the client. I don't know of another way... That's a very good question tho. – AllJs Mar 14 '17 at 20:30
  • That wouldn't solve the problem though. 1. You would still make the XHR call with the server key (and it would be blocked by google if you restricted the key to the server's ip) 2. You would still make your server key publicly accessible, which you don't want to do. The correct way to implement XHR requests is to use the Javascript Library. https://developers.google.com/maps/documentation/geocoding/intro vs. https://developers.google.com/maps/documentation/javascript/geocoding So if you want to restrict ``YOUR_API_KEY`` to a referer you need to use the JS API. – Daniel G. Mar 17 '17 at 16:46
0
searchLatAndLngByStreet(street) {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': street }, (res, status) => {
      console.log(res, status)
      if (status == google.maps.GeocoderStatus.OK) {
        return {
          latitude: JSON.stringify(res[0].geometry.location.lat()),
          longitude: JSON.stringify(res[0].geometry.location.lng())
        }
      } 
    });
}
Flavio
  • 159
  • 1
  • 3