Removing last marker before creating a new one - google-maps

i want to create a Map with an easy function. Everytime i click, the existing Marker schould be removed and a new one schould appear at click-position.
Creating new ones works fine, but removing them doesn't work. Here the code, I tried:
var map;
var latitude, longitude;
var marker;
function placeMarker(location) {
marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: location,
});
latitude = location.lat();
longitude = locaton.lng();
document.getElementById('koordinaten').innerHTML = '<p>' + latitude + '</p>';
}
OK, comment the marker.setMap(null); i can add as much markers as i want, but i want to only have one Marker on the Map.
Can you please help me, how to remove a marker and place a new one?
Thanks

When you run this function the first time, the first line will result in an error, because marker still is undefined(doesn't have a setMap-method).
You may catch this case and bypass the first line :
if(typeof marker!=='undefined'){
marker.setMap(null);
}
But a better approach would be to use always the same marker and apply the new position:
function placeMarker(location) {
//when marker is undefined, create a marker
if(typeof marker==='undefined'){
marker = new google.maps.Marker({
map: map
});
}
//set the position
marker.setPosition(location);
latitude = location.lat();
longitude = locaton.lng();
document.getElementById('koordinaten').innerHTML
= '<p>' + latitude + '</p>';
}

Related

Google Maps V3 InfoWindow ignores latLng position

My map has no markers. In response to a click on the map, it pops up an infowindow with Lat/long shown in decimal to 5 dp and in Degrees minutes seconds. An open window is always closed prior to responding to a new click. The position is specified by position: latLng, but the infowindow is ALWAYS at the top left. I've spent days on this, and I feel I'm missing something. Code snippet below. Any ideas?
google.maps.event.addListener(map, 'click', function (event) {
var lat = event.latLng.lat(),
lng = event.latLng.lng(),
latLng = event.latLng,
strHtml;
//
// strHtml build code omitted but succesfully uses lat and lng to produce
// e.g. Latitude : 51.72229 N (51° 43' 20'' N)
// Longitude : 1.45827 E (1° 27' 30'' E)
//
// If an infowindow is open, then close it
if (openedInfoWindow != null) openedInfoWindow.close();
// latLng monitored to check it is there before use in infowindow
alert(latLng); // returns correct values which position then ignores!
var infoWindow = new google.maps.InfoWindow({
position: latLng,
content: strHtml,
maxWidth: 420
});
// Open infoWindow
infoWindow.open(map,this);
// Remember the opened window
openedInfoWindow = infoWindow;
// Close it if X box clicked
google.maps.event.addListener(infoWindow, 'closeclick', function() {
openedInfoWindow = null;
});
});
You have several problems with this code. The second parameter of the infowindow's open method has to be an MVCObject in the Core API only the Marker class can be used as an anchor. You should not need to set the infowindow variable to null and create a new infowindow object each time. You only need a single infowindow and then change its content and position. This way there is only one infowindow shown at a time.
Here is a fiddle of a working example: http://jsfiddle.net/bryan_weaver/z3Cdg/
relevant code:
google.maps.event.addListener(map, 'click', function (evt) {
var content = "<div class='infowindow'>";
content += "Latitude: " + evt.latLng.lat() + "<br/>";
content += "Longitude: " + evt.latLng.lng() + "</div>";
HandleInfoWindow(evt.latLng, content);
});
function HandleInfoWindow(latLng, content) {
infoWindow.setContent(content);
infoWindow.setPosition(latLng);
infoWindow.open(map);
}
The 2nd (optional)argument of infoWindow.open() is expected to be an MVCObject that exposes a position-property.
the this argument in the callback refers to a google.maps.Map-Instance(map), which is an MVCObject, but doesn't have a position-property.
Remove the 2nd argument from infoWindow.open(map,this); .

Failed in clear markers in Google Map API3

I have created a function to add the marker when there is no marker on map or remove the original marker and added a new one to replace it. However, i can add the first part of script successfully to add the marker on map. however, the original marker can not be removed and new marker could not added when i click the map again. Can anyone suggest what is the problem?
/*Create a listener to record the Click event of the google map and define it as the starting point (i.e. Origin in Google Direction
service*/
google.maps.event.addListener(map, 'click', function(event) {
if (origin == null) {
origin = event.latLng;
lat = origin.lat();
lng = origin.lng();
UpdateLatLng();
var startimage = 'images/Start4.png';
StartMarker = new google.maps.Marker({
map: map,
position: origin,
icon: startimage
});
} else {
//Relocate the Starting point and assign the new position to Textbox
alert ("The starting point was relocated on screen");
StartMarker.setMap(null);
directionsDisplay.setMap(null);
directionsDisplay.setPanel(null);
directionsDisplay.setDirections({routes: []});
var origin = event.latLng;
lat = origin.lat();
lng = origin.lng();
UpdateLatLng();
var startimage = 'images/Start4.png';
StartMarker = new google.maps.Marker({
map: map,
position: origin,
icon: startimage
});
}
});
This works for me:
var StartMarker = null;
/*Create a listener to record the Click event of the google map and define it as the starting point (i.e. Origin in Google Direction
service*/
google.maps.event.addListener(map, 'click', function(event) {
if (!StartMarker) {
origin = event.latLng;
lat = origin.lat();
lng = origin.lng();
StartMarker = new google.maps.Marker({
map: map,
position: origin
});
} else {
//Relocate the Starting point and assign the new position to Textbox
alert ("The starting point was relocated on screen");
StartMarker.setMap(null);
var origin = event.latLng;
lat = origin.lat();
lng = origin.lng();
StartMarker = new google.maps.Marker({
map: map,
position: origin
});
}
});
working example
Try to use the existing Marker like:
// Will change the poisition
StartMarker.setPosition(origin);
// Will change the Icon
StartMarker.setIcon(startimage);

How to move marker on the map dynamically on click of the button

I am adding Marker dynamically and adding click event to every marker added on the map. This is the way, I am adding the marker on the map.
var pin = new google.maps.LatLng(Y, X);
var marker = new google.maps.Marker({ position: pin, map: map1 });
google.maps.event.addListener(marker, 'click', pinClicked);
marker.setMap(map1);
In the click event, based on certain conditions I am displaying a popup with certain details and buttons. One button is to close the popup and the other button is to Move marker.
What I want is when I click the Move marker button, I want the marker to be moved.
I don't want to set the draggable property to true by default, as it will be allowing the marker to be dragged when added on the map.
Marker should be draggable only when the button on the popup is clicked.
How can I get this working.
Any help is appreciated.
Thanks.
I've created this jsFiddle which shows you how to do it.
var markers = [];
function initialize() {
var myLatLng1 = new google.maps.LatLng(50.965049,5.484231);
var myLatLng2 = new google.maps.LatLng(50.97,5.474231);
var myOptions = {
zoom: 14,
center: myLatLng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
for (var i = 0; i < 2; i++) {
var marker = new google.maps.Marker({
position: i === 0 ? myLatLng1 : myLatLng2,
map: map,
title: 'Galaconcert ' + i,
id: i
});
markers[i] = marker;
manageBindings(marker);
}
function manageBindings(marker) {
var id = marker.id;
google.maps.event.addListener(marker, 'click', function(ev) {
var contentString =
'<div id="infowindow">' +
'Nice infowindow ' + id + '<br />' +
'<button class="move" data-id="' + id + '">move me</button> ' +
'<button class="close" data-id="' + id + '">close me</button><br />' +
'</div>'
;
marker.infowindow = new google.maps.InfoWindow();
marker.infowindow.setContent(contentString);
marker.infowindow.open(map, marker);
});
}
}
$(function(){
$('button.move').live('click', function(){
var id = $(this).data('id');
markers[id].setDraggable(true);
});
$('button.close').live('click', function(){
var id = $(this).data('id');
markers[id].infowindow.close();
});
initialize();
});
You should keep all your created markers in an array so you can access them. In an infowindow you store the reference to that array - in my example it's in button's data attribute. Then when anything happens in infowindow, you are able to access the particular marker and set it's draggable option to true.
The code should be refactored and should not use live but you should have the idea.
There is a method for Markers that allows you to set their draggable option.
Then also change the button to say place marker so that when you've dragged the marker to where you want it to be you can click it again to place the marker and set the draggable property to false again.
new google.maps.event.addListener(button, 'click', function(){
if(button.status == "Move"){
marker.setDraggable(true);
} else {
marker.setDraggable(false);
}
});
Please note this is psuedo code just highlighting the setDraggable function.
Google markers have property setDraggable by which it can be set marker draggable to true or false.
marker.setDraggable(true); or
marker.setDraggable(false);

Get marker id in google maps

I want to pass related marker id by clicking marker on google map. I am using marker.getId() function to retrieve marker id. But the marker id is not passing along with url. How can i do this? Any Help?
function AddressMap(lat,lang,markerid)
{
var latLng = new google.maps.LatLng(lat,lang);
var marker = new google.maps.Marker({
'map': map,
position: latLng,
'latitude' :lat,
'longitude' :lang,
icon: image,
shadow: shadow,
id: markerid
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
window.location = "www.cickstart.com/" + marker.getId();
});
}
you can try directly to access the id:
google.maps.event.addListener(marker, 'click', function() {
window.location = "www.cickstart.com/" + marker.id;
});
the best way to do this is add a metadata to marker
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
if you have so many marker push the marker to array marker.
You can add any data that you want. and simply call it, set it or get it.
the sample like this one:
markers[0].metadata.id

how to clear previous google map markers so only one is on the map at a time

I am trying to make this map only allow one marker on the page at any time but when I click a new marker is placed along with old ones.
Does anyone know how you would make this happen?
google.maps.event.addListener(map, 'click', function(event) {
//set up variables
var clickLat = event.latLng.lat();
var clickLng = event.latLng.lng();
//show lat and long
var loc = document.getElementById("location");
var info = "Latitude: "+clickLat+" "+", longitude: "+clickLng;
loc.innerHTML = info;
//place marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(clickLat, clickLng),
map: map,
animation: google.maps.Animation.DROP
});
});
I believe your answer is in the Google Mapa API. You just have to set the map of your old marker to null.
Read this: http://code.google.com/apis/maps/documentation/javascript/overlays.html#RemovingOverlays
Another option would be to have a single marker variable and update the position of the marker when someone clicks on the map.
declare a Marker field:
private Marker marker;
then, for the setOnMapClickListener method of your GoogleMap object, do the following:
#Override
public void onMapClick(LatLng point) {
if(marker!=null) marker.remove();
markerSelectedPlace = new MarkerOptions().position(point).title(
"dfsdfsdfs dfsdfsdf");
marker = mMap.addMarker(markerSelectedPlace);
mMap.addMarker(markerSelectedPlace);
marker.showInfoWindow();
}