10

I know place_id, and I need to know it's coordinates.

I can do GET https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE

which gives me something like that:

```   "results" : [
      {
         "address_components" : [...],
         "formatted_address" : "New York County, NY, USA",
         "geometry" : {
            "bounds" : {...},
            "location" : {
               "lat" : 40.7830603,
               "lng" : -73.9712488
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {...}
         },
         "partial_match" : true,
         "place_id" : "ChIJOwE7_GTtwokRFq0uOwLSE9g",
         "types" : [...]
      }
   ],
   "status" : "OK"
```

but I need to do it via javascript api.

I don't have any maps on my page, just need to get the coordinates.

Verma
  • 8,199
  • 2
  • 15
  • 17
eawer
  • 1,398
  • 3
  • 13
  • 25

5 Answers5

12

From the example in the Google Maps Javascript API v3 documentation (with your place_id):

var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);

service.getDetails(request, function(place, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location
    });
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(place.name);
      infowindow.open(map, this);
    });
    map.fitBounds(place.geometry.viewport);
  }
});

working fiddle

code snippet:

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var request = {
    placeId: 'ChIJOwE7_GTtwokRFq0uOwLSE9g'
  };

  var infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);

  service.getDetails(request, function(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
      });
      map.fitBounds(place.geometry.viewport);
    }
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
7

You don't need a map. It is a Restful web service that returns a JSON string. In your application, you only need to send a HTTP request to

GET https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE

and then parse the JSON string returned, and retrieve the latlng inside.

If you are using Jquery in your web app, you may do

    $.ajax({
            type: "GET",
            url: "https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJOwE7_GTtwokRFq0uOwLSE9g&key=KEY_GOES_HERE",
            dataType: "text", 
            success: function (yourJSONstring){
                var respJson = $.parseJSON(yourJSONstring);  

            // then something like ... 
            // respJson.results[0].geometry.location.lat;
            // respJson.results[0].geometry.location.lng; 


            },
            error: function (xhr) {
            }
        }); 
Gene Bo
  • 11,284
  • 8
  • 90
  • 137
Man Coding
  • 442
  • 5
  • 5
  • 1
    I can't see the reason why this answer is getting upvoted. The OP said `but I need to do it via javascript api.` but this answer does not show that. – maswerdna Feb 06 '20 at 23:07
1

it is happening because the location property is of type google.maps.LatLng.

For you to get the lat and lng the following functions can be used: example:

place.geometry.location.any_function_below()

1. toString():  Converts to string representation.eg ((37.8042802, -122.41364429999999))
2. lat(): Returns the latitude in degrees.
3. lng(): Returns the longitude in degrees.
4. toJSON(): Converts to JSON representation ({lat: "", lng: ""}).
5. toUrlValue(precision?:number): Returns a string of the form "lat,lng" for this LatLng. We round the lat/lng values to 6 decimal places by default.

you can read more here: https://developers.google.com/maps/documentation/javascript/3.exp/reference#LatLng.

ben
  • 6,000
  • 5
  • 35
  • 42
1
`//only add these line under function`
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']);
var lng = place.geometry.location.lng();
var lat = place.geometry.location.lat();
var latlng = {lat , lng};
console.log(latlng);

});

  • 1
    actually sir if you use this code of snippet [https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-directions] remove setFields that under origin-input and destination-input.use above function autocomplete.addListener that is already given but add autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']); var lng = place.geometry.location.lng(); var lat = place.geometry.location.lat(); var latlng = {lat , lng};console.log(latlng); – Muhammad Yasir Apr 17 '19 at 13:25
-4

You can retrieve it location like this

var obj = JSON.parse(yourJSONstring);


obj.results[0].geometry.location.lat;
obj.results[0].geometry.location.lng; 
Verma
  • 8,199
  • 2
  • 15
  • 17