01.
function
initAutocomplete() {
02.
var
map =
new
google.maps.Map(document.getElementById(
'map'
), {
03.
center: {lat: -33.8688, lng: 151.2195},
04.
zoom: 13,
05.
mapTypeId:
'roadmap'
06.
});
07.
08.
09.
var
input = document.getElementById(
'pac-input'
);
10.
var
searchBox =
new
google.maps.places.SearchBox(input);
11.
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
12.
13.
14.
map.addListener(
'bounds_changed'
,
function
() {
15.
searchBox.setBounds(map.getBounds());
16.
});
17.
18.
19.
20.
searchBox.addListener(
'places_changed'
,
function
() {
21.
var
places = searchBox.getPlaces();
22.
23.
if
(places.length == 0) {
24.
return
;
25.
}
26.
27.
markers.forEach(
function
(marker) {
28.
marker.setMap(
null
);
29.
});
30.
markers = [];
31.
32.
33.
var
bounds =
new
google.maps.LatLngBounds();
34.
places.forEach(
function
(place) {
35.
if
(!place.geometry) {
36.
console.log(
"Returned place contains no geometry"
);
37.
return
;
38.
}
39.
var
icon = {
40.
url: place.icon,
41.
size:
new
google.maps.Size(71, 71),
42.
origin:
new
google.maps.Point(0, 0),
43.
anchor:
new
google.maps.Point(17, 34),
44.
scaledSize:
new
google.maps.Size(25, 25)
45.
};
46.
47.
48.
markers.push(
new
google.maps.Marker({
49.
map: map,
50.
icon: icon,
51.
title: place.name,
52.
draggable:
true
,
53.
animation: google.maps.Animation.DROP,
54.
position: place.geometry.location
55.
}));
56.
57.
if
(place.geometry.viewport) {
58.
59.
bounds.union(place.geometry.viewport);
60.
}
else
{
61.
bounds.extend(place.geometry.location);
62.
}
63.
google.maps.event.addListener(markers,
'dragend'
,
function
(event) {
64.
document.getElementById(
"latitude"
).value =
this
.getPosition().lat();
65.
document.getElementById(
"longitude"
).value =
this
.getPosition().lng();
66.
});
67.
68.
69.
70.
});
71.
map.fitBounds(bounds);
72.
73.
});
74.
}