Google Maps v3 set single marker point on map click - javascript

Right now I have google map code that will set a single marker on a map. What I want is for that single marker to be moved to whatever coordinates the user clicks on. I only want 1 marker on the map, so I need that single marker to be moved to whatever location is clicked. Any help is appreciated. Thanks!
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
myListener = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
google.maps.event.addListener(map, 'drag', function(event) {
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag === true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
map.setCenter(location);
var markerPosition = marker.getPosition();
populateInputs(markerPosition);
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
}

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map_canvas {height:600px;width:800px}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markersArray = [];
function initMap()
{
var latlng = new google.maps.LatLng(41, 29);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// add a click event handler to the map object
google.maps.event.addListener(map, "click", function(event)
{
// place a marker
placeMarker(event.latLng);
// display the lat/lng in your form's lat/lng fields
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
});
}
function placeMarker(location) {
// first remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// add marker in markers array
markersArray.push(marker);
//map.setCenter(location);
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body onload="initMap()">
<div id="map_canvas"></div>
<input type="text" id="latFld">
<input type="text" id="lngFld">
</body>
</html>

The current answers do a lot more work than is necessary by removing and re-adding the marker(s). The best way to do this is to use the setPosition() function that the Google Maps API provides for this purpose.
Here is your code modified to use setPosition() to move the pointer:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map_canvas { height:600px; width:800px }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker;
myListener = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map, 'drag', function(event) {
placeMarker(event.latLng);
});
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag === true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
}
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
google.maps.event.addListener(marker, "drag", function (mEvent) {
populateInputs(mEvent.latLng);
});
}
populateInputs(location);
}
function populateInputs(pos) {
document.getElementById("t1").value=pos.lat()
document.getElementById("t2").value=pos.lng();
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
<input type="text" id="t1">
<input type="text" id="t2">
</body>
</html>

You can try:
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
marker.setPosition(marker_position);
})

Make a global javascript variable "marker".
Then in your listener add the if marker exists statement and remove it if true
myListener = google.maps.event.addListener(map, 'click', function(event) {
if(marker){marker.setMap(null)}
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});

try this
if (marker) { marker.setMap(null) }
marker = new google.maps.Marker({ position: event.latLng, map: map });

Burak Erdem answer works fine, but actually you dont need and array to do that, it is enough one var since it is only one last marker, becouse when you set a new one, you delete inmediatly the last one. I did it with this few lines and it worked fine:
var map;
var lastMarker;
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(-25.363882, 131.044922),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(map_canvas, map_options)
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
if (lastMarker != null)
lastMarker.setMap(null);
var marker = new google.maps.Marker({
position: location,
map: map
});
lastMarker = marker;
}
google.maps.event.addDomListener(window, 'load', initialize);

I accomplished this with the following:
// create a new marker
var marker = new google.maps.Marker({
});
//add listener to set the marker to the position on the map
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng);
marker.setMap(map);
marker.setAnimation(google.maps.Animation.DROP);
});
It creates a marker and then move it to each mouse click location...
I also added a drop marker animation as well.
Instead of creating multiple markers this creates one marker and moves it to the clicked location.

Related

Set Google map marker

Hi i have a Google Map that automatically check for user location and put the location to center. I am having problem with putting the marker at the center. I am currently adding marker when you click somewhere.
I also want to clear existing markers when another position is clicked.
var markers = [];
window.onload = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
var mapOptions = {
center: new google.maps.LatLng(21.3891, 39.8579),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// This event listener calls addMarker() when the map is
// clicked.
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addListener(map, 'click', function(e) {
document.getElementById("lat").value = (e.latLng.lat());
document.getElementById("lng").value = (e.latLng.lng());
div = document.getElementById('name');
div.style.display = "block";
div = document.getElementById('submit');
div.style.display = "block";
var element = document.getElementById('spacing');
element.style.margin = null;
});
}
#map {
height: 100%;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA-2vW1cIR0t0ZVfVdCmcxx0QEV4C3l6hk&callback=myMap"></script>
<div id="map" style="width:100%; height:505px ; z-index: 1;">
</div>
Hi added this code to the existing code to add marker to center:
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
var marker = new google.maps.Marker({ position: pos, animation:
google.maps.Animation.BOUNCE, icon: 'img/mapicon.png' });
marker.setMap(map);
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
For the secoind solution, i added this :
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
icon: 'img/mapicon.png',
map: map
});
map.panTo(position);
markers.push(marker);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function clearMarker(position, map) {
setMapOnAll(null);
}

Plotting google maps with local storage

I have created an application that allows a user to plot a flag on google maps upon a click event although once the page is refreshed all of flags are lost. I want to be able to keep the data the user has input using local storage, can anyone point me in a direction or show me sample code of how they would handle this problem? thanks.
Basic google maps code without local storage
var map;
var myCenter=new google.maps.LatLng(54.906435, -1.383944);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
//creating the event for placing the marker
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
//Funcion to place the marker on the map (flag)
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
icon:'flag.png',
map: map,
});
//open information window once marker is placed
var infowindow = new google.maps.InfoWindow({
content: 'User has placed warning'
});
infowindow.open(map,marker);
//zoom into the marker
google.maps.event.addListener(marker,'click',function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
This should do the trick ;)
function initialize()
{
var mapProp = {
center:myCenter,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
//creating the event for placing the marker
google.maps.event.addListener(map, 'click', function(event) {
writeToStorage(event.latLng);
placeMarker(event.latLng);
});
setupStorage();
readFromStorage();
}
function setupStorage() {
if(typeof(localStorage) === "undefined") {
// If localStorage isn't supported, fake it.
// Won't persist between sessions.
localStorage = {};
}
localStorage.locations = localStorage.locations || [];
}
function writeToStorage(location) {
localStorage.locations.push(location);
}
function readFromStorage() {
localStorage.locations.forEach(function(location) {
placeMarker(location);
});
}
//Funcion to place the marker on the map (flag)
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
icon:'flag.png',
map: map,
});
//open information window once marker is placed
var infowindow = new google.maps.InfoWindow({
content: 'User has placed warning'
});
infowindow.open(map,marker);
//zoom into the marker
google.maps.event.addListener(marker,'click',function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Let me know if you have any trouble understanding any of it.
var map = {};
var polyOptions = {};
$(document).ready(function () {
map = new google.maps.Map(document.getElementById('MapDiagram'), {
zoom: 5.4,
center: new google.maps.LatLng(40, -10),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true
});
polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
});
map.setCenter(new google.maps.LatLng(coord1, coord2));

Google Maps API: Multiple GeoJson layers with MarkerClusterer + toggle

I have a problem with my GeoJson layers which I want to cluster (with MarkerClusterer) and then be able to show and hide them via checkboxes or similar. Therefore I tried something like the code below:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.515696, 13.392624),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var bounds = new google.maps.LatLngBounds();
var barLayer = new google.maps.Data();
var cafeLayer = new google.maps.Data();
barLayer.loadGeoJson('json/eat_drink/bar.geojson');
cafeLayer.loadGeoJson('json/eat_drink/cafe.geojson');
var markerClusterer = new MarkerClusterer(map);
var infowindow = new google.maps.InfoWindow();
markerClusterer.setMap(map);
function displayMarkers(layer) {
var layer = layer;
google.maps.event.addListener(layer, 'addfeature', function (e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
// open the infoWindow when the marker is clicked
google.maps.event.addListener(marker, 'click', function (marker, e) {
return function () {
var myHTML = e.feature.getProperty('name');
infowindow.setContent("<div style='width:150px; text-align: center;'>"+myHTML+"</div>");
infowindow.setPosition(e.feature.getGeometry().get());
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-30)});
infowindow.open(map, marker);
};
}(marker, e));
markerClusterer.addMarker(marker);
bounds.extend(e.feature.getGeometry().get());
map.fitBounds(bounds);
map.setCenter(e.feature.getGeometry().get());
}
});
layer.setMap(null);
google.maps.event.addListener(map, "click", function () {
infowindow.close();
});
};
document.getElementById('bar').onclick = function(){ // enable and disable markers
if(document.getElementById('bar').checked == true){
displayMarkers(barLayer);
}else{
return null;
}
};
}
Unfortunatley this doesn't work and I don't no exactly why.
If I remove the displayMarkers() function around the code and replace "layer" with the desired GeoJson layer, e.g. "barLayer", it works just fine.
Since I will end up with tons of GeoJason layers I would prefer a "compact" solution like this insted of copying the code multiple times. Have you guys any ideas how to do that properly?
I'm afraid I haven't done much more than refactor your code. Could you give this a try, and if it doesn't work specify exactly what doesn't work?
function displayMarkers(layer, map, markerClusterer) {
google.maps.event.addListener(layer, 'addfeature', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
// open the infoBox when the marker is clicked
google.maps.event.addListener(marker, 'click', function(e) {
var myHTML = e.feature.getProperty('name');
var infowindow = new google.maps.InfoWindow();
infowindow.setContent("<div style='width:150px; text-align: center;'>" + myHTML + "</div>");
infowindow.setPosition(e.feature.getGeometry().get());
infowindow.setOptions({
pixelOffset: new google.maps.Size(0, -30)
});
infowindow.open(map, marker);
google.maps.event.addListener(map, "click", function() {
infowindow.close();
});
});
markerClusterer.addMarker(marker);
var bounds = new google.maps.LatLngBounds();
bounds.extend(e.feature.getGeometry().get());
map.fitBounds(bounds);
map.setCenter(e.feature.getGeometry().get());
}
});
layer.setMap(null);
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.515696, 13.392624),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var barLayer = new google.maps.Data();
var cafeLayer = new google.maps.Data();
barLayer.loadGeoJson('json/eat_drink/bar.geojson');
cafeLayer.loadGeoJson('json/eat_drink/cafe.geojson');
var markerClusterer = new MarkerClusterer(map);
markerClusterer.setMap(map);
document.getElementById('bar').onclick = function() { // enable and disable streetViewControl
if (document.getElementById('bar').checked == true) {
displayMarkers(barlayer, map, markerClusterer);
} else {
return null;
}
};
}

Uncaught ReferenceError: pos is not defined

js:
var map;
function initialize() {
$('#refreshmap').on('click',initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, 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(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible:true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function(){
marker.setVisible(true);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html:
<div id="map-canvas"></div>
<button type="button" id="button" class="map_buttons button_style">Add marker</button>
The above code is for display marker on current location by clicking a button.Map is showing the current location but marker is not working.
I am getting this error in console "Uncaught ReferenceError: pos is not defined".
Try this:
var map;
var pos;
function initialize() {
$('#refreshmap').on('click', initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, 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(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible: true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function () {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function () {
marker.setVisible(true);
});
}
Basically, declare var pos in the global scope, and remove var while initializing pos
The issue is that
During creation of the marker object, pos is undefined in the scope
try to declare pos global, like your map
var map;
var pos;

Get Latitude and Longitude on click event from Google map

I have implemented the Google map successfully. But one more thing has left to do. I need to retrieve the Longitude and Latitude data when the user clicks on the map (any co-ordinates). My entire code looks like this:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(<?=$decimalValueLon?>,<?=$decimalValueLat?>);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// marker STARTS
var marker = new google.maps.Marker({
position: myLatlng,
title:"Click to view info!"
});
marker.setMap(map);
// marker ENDS
// info-window STARTS
var infowindow = new google.maps.InfoWindow({ content: "<div class='map_bg_logo'><span style='color:#1270a2;'><b><?=$row->bridge_name?></b> (<?=$row->bridge_no?>)</span><div style='border-top:1px dotted #ccc; height:1px; margin:5px 0;'></div><span style='color:#555;font-size:11px;'><b>Length: </b><?=$row->bridge_length?> meters</span></div>" });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
// info-window ENDS
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>`
Thanks in advance !
You can add a click-handler like you have a load handler:
google.maps.event.addListener(map, "click", function (e) {
//lat and lng is available in e object
var latLng = e.latLng;
});
<script>
var map;
function init_map() {
var opts = { 'center': new google.maps.LatLng(35.567980458012094,51.4599609375), 'zoom': 5, 'mapTypeId': google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById('mapdiv'), opts);
google.maps.event.addListener(map,'click',function(event) {
document.getElementById('latlongclicked').value = event.latLng.lat()
document.getElementById('lotlongclicked').value = event.latLng.lng()
});
google.maps.event.addListener(map,'mousemove',function(event) {
document.getElementById('latspan').innerHTML = event.latLng.lat()
document.getElementById('lngspan').innerHTML = event.latLng.lng()
});
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>

Categories

Resources