Google maps clear all markers before placing new one - google-maps

I'm trying to place a marker on click in google maps along with populating input boxes with the lat and lng. I need the code to clear all the existing markers first before placing the new marker and updating the lat and lng. everything works except when I add code to try clear all the markers.
The below code works perfectly but does not clear the old markers before placing the new one.
Thank you.
Working code without clearing existing markers...
<div id="map"></div>
<script>
var map;
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
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);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
</script>
Not working code with clearing markers before adding a new one...
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
clearOverlays();
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
Thank you.

seem you have placed the code in the wrong place .. try
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
clearOverlays();
marker = new google.maps.Marker({
map: map,
draggable: false
});
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker.setPosition(marker_position);
markersArray.push(marker);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray = [];
}
</script>

Related

Get latitude and longitude of multiple marker (onclick)

I have multiple markers in my map.
How to create a listener to multiple markers and get their latitude and longitude?
When I tried that event listener at one marker, it works. But when I tried that event listener with my multiple marker, it doesnt work.
Here is my code :
var jakarta = new google.maps.LatLng(-6.211544, 106.845172);
var shelterpoint = [];
var shelterName = [];
<?php while ($row = mysql_fetch_array($result)) { ?>
shelterpoint.push(new google.maps.LatLng(<?=$row['Latitude']?>, <?=$row['Longitude']?>));
shelterName.push("<?=$row['Shelter_Name']?>");
<?php } ?>
var markers = [];
var iterator = 0;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
center: jakarta
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
drop();
google.maps.event.addListener(marker, "click", function (event) {
alert(this.position);
});
}
function drop() {
for (var i = 0; i < shelterpoint.length; i++) {
setTimeout(function() {
addMarker();
}, i * 10);
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: shelterpoint[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title:shelterName[iterator]
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
Please refer the link below.
http://jsfiddle.net/xJ26V/1/
var mapOptions = {
center: new google.maps.LatLng(-33.92, 151.25),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

Google Map Zoom To Fit

I have developed a map that uses a geo-coordinate from a database using a cluster marker example. I have tried to make it zoom automaticly by using LatLngBounds();
<script type="text/javascript">
function initialize() {
var center = new google.maps.LatLng(9.4419, 9.1419);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = [];
// create the infowindow out of the for boucle
var infoWindow = new google.maps.InfoWindow;
var bounds = new google.maps.LatLngBounds();
for ( var i = 0; i < latlng.length; i++ ) {
var latLng = new google.maps.LatLng(latlng.lat,latlng.lng);
var html = 'test show in infowondow';
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon:"/img/icon1.jpg",
title:"test title",
});
// call to the function....
bindInfoWindow(marker, map, infoWindow, html);
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
// create a function bindInfoWindow
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
make bounds global.
then after
var latLng = new google.maps.LatLng(latlng.lat,latlng.lng);
EDIT: and as Marcelo pointed out change this to:
var latLng = new google.maps.LatLng(latlng[i].lat,latlng[i].lng);
add:
bounds.extend(latLng)
after
var markerCluster = new MarkerClusterer(map, markers);
add:
map.fitBounds(bounds);

Google Maps API v3 - Arrays and InfoWindows

I'm been trying to make an infowindow for each of my markers for a while now but cant get it to work.
This is what I came up with:
for(var i=0; i<markery.length; i++)
{
var latt = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var nazwa = markery[i].attributes.getNamedItem("nazwa").nodeValue;
var rozmiar = new google.maps.Size(30,23);
var punkt_startowy = new google.maps.Point(0,0);
var punkt_zaczepienia = new google.maps.Point(15,12);
var ikona = new google.maps.MarkerImage(ikona_url, rozmiar, punkt_startowy, punkt_zaczepienia);
markert.push(new google.maps.Marker({
position: new google.maps.LatLng(latt,lon),
title: nazwa,
icon: ikona,
map: map,
content: nazwa
}));
google.maps.event.addListener(marker, 'click', function() {
var info = new google.maps.InfoWindow({content: this.content});
});
}
And the full code is:
<script type="text/javascript">
var map;
var marker1;
var markert = [];
var lati;
var loni;
var infowindow;
I start the map:
function initialize() {
lat = 50.42952;
long = 15.60059;
var latlng = new google.maps.LatLng(lat, long);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor:'crosshair',
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
dymek = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function(event) {
add_marker(event.latLng, 'Your new marker', 'Your new marker' );
});
}
This function gets the address of the clicked point:
function findAddress(event) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infoWindow.setContent(results[0].formatted_address);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
}
});
}
This function adds a new marker on the map where I clicked:
function add_marker( pos, pos_title, pos_str ) {
marker1 = new google.maps.Marker( {
position: pos,
map: map,
draggable: true,
title: pos_title
});
map.setZoom(15);
map.setCenter(marker1.getPosition());
LoadMarkers();
}
This function loads the nearby points that are near the marker I created in the function above:
function LoadMarkers()
{
var adres='add.xml?lat='+lati+'&long='+loni;
jx.load(adres, function(xml)
{
var markery = xml.getElementsByTagName("marker");
for(var i=0; i<markery.length; i++)
{
var latt = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var nazwa = markery[i].attributes.getNamedItem("nazwa").nodeValue;
var markert = addMarkers(latt,lon,ikona_url,nazwa);
}
},'xml','get');
}
This function actually ads the nearby markers on the map. These markers are the ones that I want the infowindow to show:
function addMarkers(latt,lon,ikona_url,nazwa)
{
var rozmiar = new google.maps.Size(30,23);
var punkt_startowy = new google.maps.Point(0,0);
var punkt_zaczepienia = new google.maps.Point(15,12);
var ikona = new google.maps.MarkerImage(ikona_url, rozmiar, punkt_startowy, punkt_zaczepienia);
markert.push(new google.maps.Marker({
position: new google.maps.LatLng(latt,lon),
title: nazwa,
icon: ikona,
map: map,
animation: google.maps.Animation.DROP }));
google.maps.event.addListener(markert, 'tilesloaded', function() {
var info = new google.maps.InfoWindow({content: nazwa});
});
}
You're not actually opening the infowindow at any point. Please review this documentation and example, and adapt your code accordingly. You actually need to use the open method for infowindow.

API V3 Update marker position dynamically

I have this code that reads data from an xml file and puts the marker on the map.
What i want to do is to read the xml file automatically every 5 seconds, and so update the position of the marker.
I tried adding setInterval to the function, but the problem is that the previous marker is not deleted. Just add another marker to the map and so on.
(I dont want the entire map updated, just the marker)
<script type="text/javascript">
var map = null;
function createMarker(latlng, html) {
var contentString = html;
var image = new google.maps.MarkerImage('http://www.google.com/mapfiles/markerA.png',
new google.maps.Size(20, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var shadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: shadow,
icon: image,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-18.432713,-70.317993),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
setInterval(function() {
downloadUrl("data.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var html = "<strong>Taxi Arica</strong></br><strong>Latitud:</strong> " + markers[i].getAttribute("lat") + "</br><strong>Longitud:</strong> " + markers[i].getAttribute("lng");
var marker = createMarker(point,html);
}
});
},5000);
}
var infowindow = new google.maps.InfoWindow(
{size: new google.maps.Size(150,50)});
</script>
To update the position of a marker, you should call setPosition:
var new_marker_position = new google.maps.LatLng(53.345735, -6.259548);
marker.setPosition(new_marker_position);

InfoWindow on Marker using MarkerClusterer

This is my html code. I've try anything to add an infowindow on the markers but it don't wanna work. My data is loading from the "Alle_Ortswahlen.page1.xml" file.
Do anyone have an idea how can I add infoWindow to each marker?
<script type="text/javascript">
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
</script>
Before the for cycle, make an empty infowindow object.
var infowindow = new google.maps.InfoWindow();
Than in the for cycle, after the marker, add an event listener, like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
There is some closure magic happening when passing the callback argument to the addListener method. If you are not familiar with it, take a look at here:
Mozilla Dev Center: Working with Closures
So, your code should look something like this:
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var infowindow = new google.maps.InfoWindow();
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
So what you need to do is add some code, inside your for-loop, associating an infowindow onclick event handler with each marker. I'm assuming you only want to have 1 infowindow showing at a time, i.e. you click on a marker, the infowindow appears with relevant content. If you then click on another marker, the first infowindow disappears, and a new one reappears attached to the other marker. Rather than having multiple infowindows all visible at the same time.
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
// just create one infowindow without any content in it
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent(markers[i].getAttribute("Field123"));
infowindow.open(map, this);
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});