JavaScript GoogleMaps move placemarker - javascript

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>

Related

Google Place Autocomplete API Showing Blank Map

I'm using the following script to show auto complete place API on my webpage, everything is working fine but map is not showing, i have tried multiple solutions but they won't help in any way here is my script
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<script>
var map;
var marker;
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos,
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerAddress(str) {
document.getElementById("location-text-box").value = str;
}
function initialize() {
var mapOptions = {
zoom: 8
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
//updateMarkerStatus('Dragging...');
//updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
// alert("drag ended");
//updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
marker = new google.maps.Marker({
position: options.position,
map: map,
draggable: true
});
// Update current position info.
google.maps.event.addListener(marker, 'dragstart', function() {
//updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
//updateMarkerStatus('Dragging...');
//updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
// alert("drag ended");
//updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */
(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
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(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
out put i'm getting is
html
<div style="width:100%; height:100%;">
<input id="location-text-box"/>
<div id="map-canvas"></div>
</div>

Autocompletion en show on map

I have tried to make autocompletion for my application and show this to my Google maps but it doesn't works well.
The code is in a seperate js file called autocomplete.js
I already have a google maps in app so I want to use the same.
The id of google map is: googleMap
The id of search button is: autosearch
The id of input is: autoinput
"use strict";
var input = document.getElementById('autoinput');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
var input = document.getElementById('autoinput');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'be'}
};
function fillInAddress() {
var place = autocomplete.getPlace();
var defaultBounds = document.getElementById('googleMap')(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('autoinput');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
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 = [];
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)
};
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);
});
};
I changed code etc but i guess i deleted something that i need.
This is the other js file for geolocation called locationSearch.js:
var google;
$( document ).ready(function() {
zoekLocatie();
});
function zoekLocatie() {
var output = document.getElementById("googleMap");
navigator.geolocation.getCurrentPosition(success, error);
output.innerHTML = "<p>Looking for your location...</p>";
if (!navigator.geolocation) {
output.innerHTML = "<p>Your browser doesn't support geolocation</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var mapProp = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
geocodeLatLng(geocoder, map, infowindow);
function geocodeLatLng(geocoder, map, infowindow) {
var input = latitude + "," + longitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(18);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
address.innerHTML = results[1].formatted_address;
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
you have a error here
use strict";
you should remove the "
And where you call your google map function ?

How to show items on google map similar to the way google shows its results

I need to show a map with multiple markers, Ive found this question which has what I am looking for but the problem is I need to show the marker of each item next to it.
<c:forEach var="product" items="products">
${product.name}
</c:forEach>
I also checked the answer of this question but did not help much.
Google Map Code
var pinColor = "FE7569";
var marker, i;
var address=[];
address[0] = "New york";
address[1] = "las vegas";
address[2] = "san francisco";
address[3] = "chicago";
// Set default map center location
var latlng = new google.maps.LatLng(latcenter,longcenter);
// Create pinShadow for each marker
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com /chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
// Function to create the dynamic marker
function pinImage(i){
return image = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/"+i+"/"+pinColor+"/", new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34));
}
// Function to run once page has loaded
function initialize(){
var geocoder=new google.maps.Geocoder();
// Set Default settigns for google map
var settings = {
zoom: 3,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP};
// Start Google Maps and assign it to div on site
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
// loop though total numner of address in array
for (var i = 0; i < address.length; i++) {
(function(i) {
// Use geocoder to grab latlong for user inputed address
geocoder.geocode( { 'address': address[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Redefine map center location
if (i == 1){ map.setCenter(results[0].geometry.location); }
// Create dynamic markers on map as per the address array
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title:address[i],
zIndex: i,
// PROBLEM CODE --- Using the function below it creates all Markers with a "1" instead of the "i" value..??
icon: pinImage(i),
shadow: pinShadow
});
}
});
})(i);
}
}
google.maps.event.addDomListener(window, 'load', initialize)
Desirable output is similar to following image, each result has a named marker and its location is shown by its associated marker on the map. I need markers to be alphabetical not numbered also based on coordinate not address.
EDIT: Changed the snippet to get the marker image from chart.apis.google.com. (I'm not sure why googlemapsmarkers.com stopped working).
You can get the url from the marker, and display it as an image. Here is a code snippet to illustrate:
<!DOCTYPE html>
<head lang="en">
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<style>
#map-canvas,
#marker-container {
width: 50%;
height: 600px;
margin: 0px;
padding: 0px;
float: left;
}
.marker-description {
padding-left: 40px;
}
.place {
padding-left: 10px;
}
.marker {
display: inline-block;
width: 21px;
height: 35px;
}
</style>
</head>
<body>
<div id="map-canvas"></div>
<div id="marker-container"></div>
<script>
var map;
var markers = [];
var pinColor = "FE7569";
// Function to create the dynamic marker
function pinImage(imagenum) {
// should check for more than 32 pins...
var ch = 'A'
var makerLetter = String.fromCharCode(ch.charCodeAt(0) + imagenum);
return image = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + makerLetter + "|" + pinColor);
}
function initialize() {
var newYork = new google.maps.LatLng(40.7773514, -73.9554338);
var mapOptions = {
zoom: 13,
center: newYork,
disableDefaultUI: true,
mapTypeControlOptions: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var request = {
location: newYork,
radius: 5000,
types: ['store']
};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
$("#marker-container").empty();
for (i = 0; i < results.length; i++) {
var place = results[i];
var placeLoc = place.geometry.location;
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location,
icon: pinImage(i)
});
markers.push(marker);
var description = $("<div class='marker-description'><image class='marker' src='" + marker.icon.url + "'></image><span class='place'>" + place.name + "</span>");
$("#marker-container").append(description);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
It sounds like you want letters instead of numbers inside your pin:
// Function to create the dynamic marker
function pinImage(i) {
var letter = String.fromCharCode(i + 65); // 'A' is 65.
return new google.maps.MarkerImage(
"http://www.googlemapsmarkers.com/v1/" + letter + "/" + pinColor + "/",
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
}
Also, you need to create objects that keep track of the address, latlng, and index of each of your markers. I suggest you use map.data to do this. https://developers.google.com/maps/documentation/javascript/reference#Data
var addresses = ['New York', 'San Francisco'];
addresses.forEach(function(address, i) {
// Create a feature.
var feature = map.data.add({
'id': i,
'properties': {'address': address}
});
// Display the feature in the list.
$('.address-list').append($('<div>')
.append($('<img>').attr('src', pinImage(i)))
.append($('<div>').text(address)));
// Do more fancy things here
// Geocode the feature and position it on the map.
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
feature.setGeometry(results[0].geometry.location);
if (i == 0) {
map.setCenter(results[0].geometry.location);
}
}
});
});
Then you can control the display of the markers like this:
map.data.setStyle(function(feature) {
return {
title: feature.getProperty('address'),
zIndex: feature.getId(),
icon: pinImage(feature.getId()),
shadow: pinShadow
};
});

Move google maps marker on Places Auto-complete

I currently have a map that displays a marker on the users geolocation. I have a text input field set to Places Auto-complete. When a user searches a city name, a new marker is placed on the location. However, the old gelocation marker remains. I want to delete the old marker or move it so only 1 marker is on the map. How can I do this?
Here is my code:
<html>
<head>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable:true
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */(
document.getElementById('location-text-box'));
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),
draggable:true
});
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(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input type="text" id="location-text-box">
<div id="map-canvas"></div>
</div>
</body>
</html>
Make your marker global, and either hide it or move it to the new location
working code snippet:
var map;
var marker;
function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Get GEOLOCATION
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
map.setCenter(options.position);
marker = new google.maps.Marker({
position: options.position,
map: map,
draggable: true
});
}
// get places auto-complete when user type in location-text-box
var input = /** #type {HTMLInputElement} */
(
document.getElementById('location-text-box'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
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(' ');
}
});
}
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=geometry,places"></script>
<div style="height:100%; width:100%">
<input type="text" id="location-text-box" />
<div id="map-canvas"></div>
</div>
File javascript.js
function initialize() {
var mapOptions, map, marker, searchBox, city,
infoWindow = '',
addressEl = document.querySelector( '#map-search' ),
latEl = document.querySelector( '.latitude' ),
longEl = document.querySelector( '.longitude' ),
element = document.getElementById( 'map-canvas' );
city = document.querySelector( '.reg-input-city' );
mapOptions = {
// How far the maps zooms in.
zoom: 8,
// Current Lat and Long position of the pin/
center: new google.maps.LatLng( 23.0224, 72.5751 ),
// center : {
// lat: -34.397,
// lng: 150.644
// },
disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
scrollWheel: true, // If set to false disables the scrolling on the map.
draggable: true, // If set to false , you cannot move the map around.
// mapTypeId: google.maps.MapTypeId.HYBRID, // If set to HYBRID its between sat and ROADMAP, Can be set to SATELLITE as well.
// maxZoom: 11, // Wont allow you to zoom more than this
// minZoom: 9 // Wont allow you to go more up.
};
/**
* Creates the map using google function google.maps.Map() by passing the id of canvas and
* mapOptions object that we just created above as its parameters.
*
*/
// Create an object map with the constructor function Map()
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.
/**
* Creates the marker on the map
*
*/
marker = new google.maps.Marker({
position: mapOptions.center,
map: map,
draggable: true
});
/**
* Creates a search box
*/
searchBox = new google.maps.places.SearchBox( addressEl );
/**
* When the place is changed on search box, it takes the marker to the searched location.
*/
google.maps.event.addListener( searchBox, 'places_changed', function () {
var places = searchBox.getPlaces(),
bounds = new google.maps.LatLngBounds(),
i, place, lat, long, resultArray,
addresss = places[0].formatted_address;
for( i = 0; place = places[i]; i++ ) {
bounds.extend( place.geometry.location );
marker.setPosition( place.geometry.location ); // Set marker position new.
}
map.fitBounds( bounds ); // Fit to the bound
map.setZoom( 15 ); // This function sets the zoom to 15, meaning zooms to level 15.
// console.log( map.getZoom() );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
latEl.value = lat;
longEl.value = long;
resultArray = places[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
city.value = citi;
}
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: addresss
});
infoWindow.open( map, marker );
} );
/**
* Finds the new position of the marker when the marker is dragged.
*/
google.maps.event.addListener( marker, "dragend", function ( event ) {
var lat, long, address, resultArray, citi;
console.log( 'i am dragged' );
lat = marker.getPosition().lat();
long = marker.getPosition().lng();
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { latLng: marker.getPosition() }, function ( result, status ) {
if ( 'OK' === status ) { // This line can also be written like if ( status == google.maps.GeocoderStatus.OK ) {
address = result[0].formatted_address;
resultArray = result[0].address_components;
// Get the city and set the city input value to the one selected
for( var i = 0; i < resultArray.length; i++ ) {
if ( resultArray[ i ].types[0] && 'administrative_area_level_2' === resultArray[ i ].types[0] ) {
citi = resultArray[ i ].long_name;
console.log( citi );
city.value = citi;
}
}
addressEl.value = address;
latEl.value = lat;
longEl.value = long;
} else {
console.log( 'Geocode was not successful for the following reason: ' + status );
}
// Closes the previous info window if it already exists
if ( infoWindow ) {
infoWindow.close();
}
/**
* Creates the info Window at the top of the marker
*/
infoWindow = new google.maps.InfoWindow({
content: address
});
infoWindow.open( map, marker );
} );
});}

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