简体   繁体   中英

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:

在此处输入图像描述

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM