Tùng Sơn
Tùng Sơn

Reputation: 75

How to get coordinates of a place using google map javascript api

I have a address, i want to display it on the map and also get the lat/lng

   <body>
    <div id="floating-panel">
          <input id="address" type="textbox" value="Sydney, NSW">
          <input id="submit" type="button" value="Geocode">
        </div>
        <div id="map"></div>
        <script>
          function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 8,
              center: {lat: -34.397, lng: 150.644}
            });
            var geocoder = new google.maps.Geocoder();

            document.getElementById('submit').addEventListener('click', function() {
              geocodeAddress(geocoder, map);
            });
          }

          function geocodeAddress(geocoder, resultsMap) {
            var address = document.getElementById('address').value;
            geocoder.geocode({'address': address}, function(results, status) {
              if (status === 'OK') {
                resultsMap.setCenter(results[0].geometry.location);
                //////////////////////////////////////////
                console.log(results[0].geometry.location);
                //////////////////////////////////////////
                var marker = new google.maps.Marker({
                  map: resultsMap,
                  position: results[0].geometry.location
                });
              } else {
                alert('Geocode was not successful for the following reason: ' + status);
              }
            });
          }
        </script>
        <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>
      </body>

I got this:

enter image description here

the map works fine but i can't get the lng/lat.

How can i get that using the Maps JavaScript API or i have to use other map API like Geocoding API

Upvotes: 1

Views: 608

Answers (1)

Christopher Ransom
Christopher Ransom

Reputation: 2058

As you can see from your own screenshot, in order to retrieve the calculated values of lat/long, you need to treat those attributes like functions.

let latVal = results[0].geometry.location.lat();
let lngVal = results[0].geometry.location.lng();

Upvotes: 1

Related Questions