Google map places API not suggesting locations in Wordpress website - javascript

I have used google places API in my WordPress website. But it is not showing suggestions as I start typing any location address:
here is my code:
body code:
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="type-selector" class="controls">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-address">
<label for="changetype-address">Addresses</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</label>
</div>
<div id="map-canvas"></div><!-- #map-canvas -->
javascript code :
google.maps.event.addDomListener( window, 'load', initMap );
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
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({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no 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);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
The issue is its not suggesting location and does not move map if I type any location and press enter button. Please help me to find the issue here ??

Related

Google maps API JS multiple markers using input fields?

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>

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

Create Google Map markers on fly

I'm Using Google Maps API, I have create page where the user search the address and the Marker pops-up on the location its all good but what I really want to do is generate markers when the user clicks anywhere on the map programtically.
JSFiddle
The following adds a click handler to the map, which adds a new marker based on the lat/long.
It then attaches a right-click handler to that marker, which removes it from the map:
google.maps.event.addListener(map, 'click', function(e) {
var marker = new google.maps.Marker({
position: e.latLng,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(e) {
this.setMap(null);
});
});
function initialize() {
var placeSearch, autocomplete;
var componentForm = {
street_number: 'long_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
country: 'long_name',
postal_code: 'long_name'
};
var mapOptions = {
center: new google.maps.LatLng(41.877461, -87.638085),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDefaultUI: true,
streetViewControl: false,
panControl: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */
(
document.getElementById('field_autocomplete'));
var autocomplete = new google.maps.places.Autocomplete(input);
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)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no 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(12); // 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(25, 34),
scaledSize: new google.maps.Size(50, 50)
}));
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 id="infowindow"><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
document.getElementById("field_latitude").value = place.geometry.location.lat();
document.getElementById("field_longitude").value = place.geometry.location.lng();
var formatted_address = place.formatted_address;
document.getElementById("field_formatted_address").value = formatted_address;
//alert(formatted_address);
document.getElementById("field_street_number").value = place.address_components[0].long_name;
//alert(place.address_components[0].long_name);
document.getElementById("field_route").value = place.address_components[1].long_name;
//alert(place.address_components[1].long_name);
document.getElementById("field_locality").value = place.address_components[2].long_name;
//alert(place.address_components[2].long_name);
document.getElementById("field_administrative_area_level_1").value = place.address_components[3].long_name;
//alert(place.address_components[3].long_name);
document.getElementById("field_postal_code").value = place.address_components[4].long_name;
//alert(place.address_components[4].long_name);
document.getElementById("field_country").value = place.address_components[5].long_name;
//alert(place.address_components[5].long_name);
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
google.maps.event.addListener(map, 'click', function(e) {
var marker = new google.maps.Marker({
position: e.latLng,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(e) {
this.setMap(null);
});
});
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('field_street_number').value = place.address_components[0].long_name;
document.getElementById('field_route').value = place.address_components[1].long_name;
document.getElementById('field_locality').value = place.address_components[2].long_name;
document.getElementById('field_administrative_area_level_1').value = place.address_components[3].long_name;
document.getElementById('field_postal_code').value = place.address_components[4].long_name;
document.getElementById('field_country').value = place.address_components[5].long_name;
document.getElementById('field_latitude').value = place.geometry.location.lat();
document.getElementById('field_longitude').value = place.geometry.location.lng();
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById('field_latitude').value = latitude;
document.getElementById('field_longitude').value = longitude;
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
});
}
}
}
initialize();
body {
background: #B04D4F;
}
.frame {
padding-top: 25px;
}
input[type="text"] {
height: 40px;
padding: 5px 10px;
width: 100%;
margin-bottom: 10px;
border: 2px solid #fff;
color: #1c1c1c;
}
label {
color: #fff;
}
#map_canvas {
width: 100%;
height: 300px;
margin: 0px 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>
<div class="container frame">
<div id="locationField">
<label for="field_autocomplete">Autocomplete Search</label>
<input id="field_autocomplete" name="field_autocomplete" type="text" placeholder="Location Search" onFocus="geolocate()" />
<div class="row">
<div class="col-sm-4">
<label for="field_street_number">Street Number</label>
<input id="field_street_number" type="text" />
</div>
<div class="col-sm-4">
<label for="field_route">Route</label>
<input id="field_route" type="text" />
</div>
<div class="col-sm-4">
<label for="field_locality">City</label>
<input id="field_locality" type="text" />
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label for="field_administrative_area_level_1">State</label>
<input id="field_administrative_area_level_1" type="text" />
</div>
<div class="col-sm-4">
<label for="field_postal_code">Zipcode</label>
<input id="field_postal_code" type="text" />
</div>
<div class="col-sm-4">
<label for="field_country">Country</label>
<input id="field_country" type="text" />
</div>
</div>
<div class="row">
<div class="col-sm-6">
<label for="field_latitude">Latitude</label>
<input id="field_latitude" type="text" />
</div>
<div class="col-sm-6">
<label for="field_longitude">Longitude</label>
<input id="field_longitude" type="text" />
</div>
<div class="col-sm-12">
<label for="field_formatted_address">Formatted Address</label>
<input type="text" id="field_formatted_address" />
</div>
</div>
</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