Google maps API JS multiple markers using input fields? - javascript

I want to be able to show multiple markers when I insert something in to searchboxes on the website. Right now I have 3 input fields which I want to increase. This is what I currently have, I have tried storing multiple searchBox values in a var like so: var markers = searchBox.getPlaces(), searchBox.getPlaces1(), searchBox.getPlaces2()
How do I extend this code to additional input fields?
<input id="pac-input" class="controls" type="text" placeholder="Search Box" /><br />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 52.728616, lng: 6.4901 },
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var input1 = document.getElementById('pac-input1');
var input2 = document.getElementById('pac-input2');
var searchBox = new google.maps.places.SearchBox(input);
var searchBox1 = new google.maps.places.SearchBox(input1);
var searchBox2 = new google.maps.places.SearchBox(input2);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input1);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
searchBox1.setBounds(map.getBounds());
searchBox2.setBounds(map.getBounds());
});
var markers = [];
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]&libraries=places&callback=initAutocomplete"
async defer></script>

related question (for autocomplete): Google Maps API autocomplete 2nd address fields on same page
Get the array of <input> elements you want to use for the SearchBox, use those to create the SearchBox objects, create a function that takes the unique identifier for the SearchBox and a reference to the SearchBox object. Use that function to process the events from each of the SearchBox objects.
var searchBoxes = document.getElementsByClassName('controls');
for (var i=0; i<searchBoxes.length;i++) {
var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
markers.push([]);
searchBox.addListener('places_changed', (function(i) {
return function() {
processSearch(i, this)
}
}(i)));
}
processSearch function:
function processSearch(uniqueId, searchBox) {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers[uniqueId].forEach(function(marker) {
marker.setMap(null);
});
markers[uniqueId] = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
if (!markers[uniqueId]) markers.push([]);
markers[uniqueId].push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.controls {
width: 100px;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<input id="pac-input3" class="controls" type="text" placeholder="Search box" />
<input id="pac-input4" class="controls" type="text" placeholder="Search box" />
<input id="pac-input5" class="controls" type="text" placeholder="Search box" />
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.728616,
lng: 6.4901
},
zoom: 13,
mapTypeId: 'roadmap'
});
var markers = [];
// Create the search boxs and link them to the UI elements.
var searchBoxes = document.getElementsByClassName('controls');
for (var i = 0; i < searchBoxes.length; i++) {
var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
markers.push([]);
searchBox.addListener('places_changed', (function(i) {
return function() {
processSearch(i, this)
}
}(i)));
}
function processSearch(uniqueId, searchBox) {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers[uniqueId].forEach(function(marker) {
marker.setMap(null);
});
markers[uniqueId] = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
if (!markers[uniqueId]) markers.push([]);
markers[uniqueId].push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" async defer></script>

Related

Google Map API returns incorrect GPS coordinates

I am using Google Maps API to allow customers to more accurately identify where their products should be delivered in a city where addresses are inaccurate.
I tried the answers here and here, but neither resolved the issue.
We place a moveable pin at the location the customer specifies, and then retrieve the GPS coordinates once the customer is satisfied with their placement and hits "continue".
The problem is that the retrieved coordinates are neither the original ones associated with the address nor the new ones associated with the last location of said pin.
function initMap() {
var latitude = -8.111735;
var longitude = -79.025550;
if(localStorage.getItem('dm-latitude')){
var latitude = localStorage.getItem('dm-latitude');
var longitude = localStorage.getItem('dm-longitude');
if(latitude!='' && longitude!=''){
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
}else{
$('.dm-clone-btn').removeClass('dm-none');
$('.dm-oroginal-btn').addClass('dm-none');
}
}
$('#dm-latitude').val(latitude);
$('#dm-longitude').val(longitude);
var myLatLng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 15,
center: myLatLng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var markers = [];
var marker = new google.maps.Marker({
position: myLatLng,
draggable:true,
title: latitude+', '+longitude
});
markers.push(marker);
marker.setMap(map);
google.maps.event.addListener(map,'click',function(event) {
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable:true,
title: event.latLng.lat()+', '+event.latLng.lng()
});
markers.push(marker);
localStorage.setItem('dm-latitude',event.latLng.lat());
localStorage.setItem('dm-longitude',event.latLng.lng());
$('#dm-latitude').val(event.latLng.lat());
$('#dm-longitude').val(event.latLng.lng());
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
});
google.maps.event.addListener(marker, 'dragend', function(event) {
markers.push(marker);
localStorage.setItem('dm-latitude',event.latLng.lat());
localStorage.setItem('dm-longitude',event.latLng.lng());
$('#dm-latitude').val(event.latLng.lat());
$('#dm-longitude').val(event.latLng.lng());
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
} );
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// more details for that place.
searchBox.addListener('places_changed', function() {
console.log('search ma');
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
title: place.name,
map: map,
draggable:true,
position: place.geometry.location
}));
console.log(place.geometry);
localStorage.setItem('dm-latitude',place.geometry.viewport.Za.i);
localStorage.setItem('dm-longitude',place.geometry.viewport.Ua.i);
$('#dm-latitude').val(place.geometry.viewport.Za.i);
$('#dm-longitude').val(place.geometry.viewport.Ua.i);
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
// console.log(place.geometry.viewport);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
You are using undocumented properties: place.geometry.viewport.Za.i and place.geometry.viewport.Ua.i.
Don't do that (those property names can and do change).
I certainly wouldn't expect any property of the viewport to be related to the actual location of a place (they are likely the north east and south west corners of a bounding box associated with the place.
// more details for that place.
searchBox.addListener('places_changed', function() {
console.log('search ma');
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
title: place.name,
map: map,
draggable:true,
position: place.geometry.location
}));
console.log(place.geometry);
localStorage.setItem('dm-latitude',place.geometry.location.lat());
localStorage.setItem('dm-longitude',place.geometry.location.lng());
$('#dm-latitude').val(place.geometry.location.lat());
$('#dm-longitude').val(place.geometry.location.lng());
$('.dm-clone-btn').addClass('dm-none');
$('.dm-oroginal-btn').removeClass('dm-none');
// console.log(place.geometry.viewport);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});

JavaScript GoogleMaps move placemarker

I'm using the following JavaScript to load GoogleMaps and center on London. The user can then move the map and place a marker for which I save the longitude and latitude. The code works fine for this.
$(document).ready(function() {
var myLatLng = {lat: 51.5073509, lng: -0.12775829999998223};
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(myLatLng),
zoom: 13
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
draggable: true,
map: map,
anchorPoint: new google.maps.Point(myLatLng)
});
google.maps.event.addListener(marker, "mouseup", function(event) {
$('#id_latitude').val(this.position.lat());
$('#id_longitude').val(this.position.lng());
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
$('#id_latitude').val(place.geometry.location.lat());
$('#id_longitude').val(place.geometry.location.lng());
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
if ($('#map-canvas').length != 0) {
google.maps.event.addDomListener(window, 'load', initialize);
}
});
I want to amend the code so that when I reload the user's information it automatically goes to the marker they set and they can move it to another location. I cannot work out how to do this. Please help.
First of all, for changing the marker's position, you should keep the marker object as a global variable after you create it so that you could edit it somewhere else outside the initialize function.
And after you have reload the user's information, you can change the position of the marker this way:
var latlng = new google.maps.LatLng(-24.397, 140.644); // new latlng here.
marker.setPosition(latlng); // marker is what you keeped global.
I don't know anything about the Django framework, if it supports callbacks or something like this, do the change work there.
var markerGlobal;
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Hello World!'
});
markerGlobal = marker;
}
function changeMarkerPosition() {
var newLatlng = new google.maps.LatLng(-24.397, 131.084);
markerGlobal.setPosition(newLatlng);
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<div>
<button onclick="changeMarkerPosition()">Click me!</button>
</div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>

How to pass a input from a HTML <form> to a Javascript function?

I need to pass input (latitude & longitude) from a <form></form> to a Javascript function that will plug the point into a heatmap. I figured out how to gather the response and store it in a variable, but now I need to append it to a list in a different function in a certain format.
HTML Form:
<form name="sightings" action="" method="GET">
<input type="text" name="area" placeholder="City, Town, etc.">
<input type="submit" value="Sighting" onClick="formResults(this.form)">
</form>
Turning <input> into a JS var:
function formResults (form) {
var areaTyped = form.area.value;
alert ("Your data has been submitted.");
return areaTyped;
}
The list of points that I need to append the variable to:
function getPoints() {
var heatmapData = [
{location: new google.maps.LatLng(37.782, -122.447), weight: 0.5},
new google.maps.LatLng(37.782, -122.445),
new google.maps.LatLng(37.782, -122.437),
new google.maps.LatLng(37.785, -122.443),
new google.maps.LatLng(37.785, -122.439),
]
return heatmapData;
}
Every point in the array heatmapData needs to be in the format new google.maps.LatLng(Latitude, Longitude). Is it possible to take my each variable from the HTML form and append them to the list of points in the proper format.
The heatmap works and looks like this: Heatmap.
But the heated spot is only the points I gave it manually. How do I connect the input from my <form> to the heatmap?
You can move your search box into the map (see the Places search box sample), then when the user selects a suggestion from the google map search, add a point to the heatmap layer and call heatmap.setData() with the updated array of points. See example below:
google.maps.event.addDomListener(window, 'load', initMap);
var heatmapData = [
{location: new google.maps.LatLng(37.782, -122.447), weight: 0.5},
new google.maps.LatLng(37.782, -122.445),
new google.maps.LatLng(37.782, -122.437),
new google.maps.LatLng(37.785, -122.443),
new google.maps.LatLng(37.785, -122.439),
];
function initMap() {
var myLatlng = new google.maps.LatLng(37.782, -122.447);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var mapCanvas = document.getElementById("map-canvas");
var map = new google.maps.Map(mapCanvas, myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
var heatmap = new google.maps.visualization.HeatmapLayer({
data: heatmapData,
map: map
});
var input = document.getElementById('area');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
heatmapData.push(place.geometry.location);
heatmap.setData(heatmapData);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
//map.fitBounds(bounds);
});
}
#mapContainer,
#map-canvas {
height: 250px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places,visualization'></script>
<form name="sightings" action="" method="GET">
<input type="text" name="area" placeholder="City, Town, etc." id="area" class="controls">
<!-- not needed anymore: <input type="button" value="Sighting" onClick="searchMap()">-->
</form>
<div id="mapContainer">
<div id="map-canvas"></div>
</div>

How to implement google map javascript api integrate with reactjs?

With reactjs i'm able to display normal map without any extra functionalities. But if i'm trying to add any extra components like "Place search box", it won't work my code. its throwing an error ("SearchBox Undefined"). Is there any way to do this integration part?
Here is my code,
var DirectionMap = React.createClass({
getDefaultProps: function () {
return {
initialZoom: 8,
mapCenterLat: 43.6425569,
mapCenterLng: -79.4073126,
};
},
componentDidMount: function (rootNode) {
var mapOptions = {
center: this.mapCenterLatLng(),
zoom: this.props.initialZoom
},
map = new google.maps.Map(this.getDOMNode(), mapOptions);
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var markers = [];
var marker = new google.maps.Marker({position: this.mapCenterLatLng(), title: 'Hi', map: map});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
this.setState({map: map});
},
mapCenterLatLng: function () {
var props = this.props;
return new google.maps.LatLng(props.mapCenterLat, props.mapCenterLng);
},
render: function () {
return (
<div className="embed-item-elem">
<input id="pac-input" className="controls" type="text" placeholder="Search Box" />
</div>
);
}
});
This line looks invalid to me:
return (
<div className="embed-item-elem">
<input id="pac-input" className="controls" type="text" placeholder="Search Box" />
</div>
);
Shouldn't you be treating that as a string of HTML, i.e.
return ('
<div className="embed-item-elem">
<input id="pac-input" className="controls" type="text" placeholder="Search Box" />
</div>
');

Google maps api customized polyline [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to create two input boxes which will autocomplete locations and then a submit button which when clicked will create a polyline between the two input locations on the map. My code does the autocompletion perfectly but is not able to mark the line between the sites on clicking the submit button. Please help.Help me in debugging.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
var input1=(document.getElementById('pac-input1'));
//var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input1);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var autocomplete = new google.maps.places.Autocomplete(input1);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
};
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
google.maps.event.addListener(submit, 'click', addLatLng);
/**
* Handles click events on a map, and adds a new point to the Polyline.
* #param {google.maps.MouseEvent} event
*/
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The body of my html file is as follows:
<input id="pac-input" class="controls" type="text" placeholder="Enter a location">
<input id="pac-input1" class="controls" type="text" placeholder="Enter another location">
<div id="type-selector" class="controls">
<input type="submit" name="submit" value="SUBMIT">
</div>
<div id="map-canvas"></div>
I get a javascript error with your code: Uncaught ReferenceError: submit is not defined
google.maps.event.addListener(submit, 'click', addLatLng);
should be:
google.maps.event.addListener(document.getElementById('submit'), 'click', addLatLng);
(but it turns out you don't need that)
Once I fix that, I only get one marker. because you only have one autocomplete:
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var autocomplete = new google.maps.places.Autocomplete(input1);
autocomplete.bindTo('bounds', map);
should be:
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var autocomplete1 = new google.maps.places.Autocomplete(input1);
autocomplete.bindTo('bounds', map);
then you need a 'place_changed' listener for autocomplete1.
If you want those positions to be the ends of your polyline, you have to add them to the path:
poly.getPath().setAt(0, marker.getPosition());
working fiddle
working code snippet:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var input = /** #type {HTMLInputElement} */
(
document.getElementById('pac-input'));
var input1 = (document.getElementById('pac-input1'));
//var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input1);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var autocomplete1 = new google.maps.places.Autocomplete(input1);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
var marker1 = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
};
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
poly.getPath().setAt(0, marker.getPosition());
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addListener(autocomplete1, 'place_changed', function () {
infowindow.close();
marker1.setVisible(false);
var place = autocomplete1.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker1.setIcon( /** #type {google.maps.Icon} */ ({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker1.setPosition(place.geometry.location);
marker1.setVisible(true);
poly.getPath().setAt(1, marker1.getPosition());
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker1);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Enter a location" />
<input id="pac-input1" class="controls" type="text" placeholder="Enter another location" />
<div id="type-selector" class="controls">
<input type="submit" name="submit" id="submit" value="SUBMIT" />
</div>
<div id="map-canvas"></div>

Categories

Resources