I have an embedded Google map in my website which has a ‘Place Autocomplete widget’ which we use to get a place ID, name etc. when searching.
I also need to get the latitude and longitude of a marked place.
JavaScript
x
62
62
1
function initMap() {
2
const map = new google.maps.Map(document.getElementById("map"), {
3
center: {
4
lat: 11.0168,
5
lng: 76.9558
6
},
7
zoom: 13,
8
});
9
10
const input = document.getElementById("pac-input");
11
12
const autocomplete = new google.maps.places.Autocomplete(input, {
13
fields: ["place_id", "geometry", "name", "formatted_address"],
14
});
15
16
autocomplete.bindTo("bounds", map);
17
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
18
19
const infowindow = new google.maps.InfoWindow();
20
const infowindowContent = document.getElementById("infowindow-content");
21
22
infowindow.setContent(infowindowContent);
23
24
const geocoder = new google.maps.Geocoder();
25
const marker = new google.maps.Marker({
26
map: map
27
});
28
29
marker.addListener("click", () => {
30
infowindow.open(map, marker);
31
});
32
autocomplete.addListener("place_changed", () => {
33
infowindow.close();
34
35
const place = autocomplete.getPlace();
36
37
if (!place.place_id) {
38
return;
39
}
40
41
geocoder.geocode({
42
placeId: place.place_id
43
}).then(({ results }) => {
44
map.setZoom(11);
45
map.setCenter(results[0].geometry.location);
46
// Set the position of the marker using the place ID and location.
47
// @ts-ignore TODO This should be in @typings/googlemaps.
48
marker.setPlace({
49
placeId: place.place_id,
50
location: results[0].geometry.location,
51
});
52
marker.setVisible(true);
53
infowindowContent.children["place-name"].textContent = place.name;
54
infowindowContent.children["place-id"].textContent = place.place_id;
55
infowindowContent.children["place-address"].textContent = results[0].formatted_address;
56
infowindow.open(map, marker);
57
}).catch((e) => window.alert("Geocoder failed due to: " + e));
58
});
59
}
60
61
window.initMap = initMap;
62
Advertisement
Answer
You can retrieve the lat/lng from the geometry
property in the Place
model you retrieve:
JavaScript
1
4
1
const place = autocomplete.getPlace();
2
var lat = place.geometry.location.lat();
3
var lng = place.geometry.location.lng();
4