API V3 Update marker position dynamically - google-maps

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

Related

Google maps clear all markers before placing new one

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>

Creating Geotagged Marker Alongside a Multiple Markers in Google Maps

I've been stuck on this issue for a while now and could really use some help. In a Google Map, I have a list of markers which are being treated as a markerArray, with their own custom icons. But along with displaying those markers, I would like for it to create a marker which is placed at the users geotagged location. I have tried merging the suggestions I've come across here on stack overflow, and have successfully gotten the users browser to center the map based off of geolocation, but whenever I try to add a marker outside of the standard var=locations, all of the markers disappear. I am providing my working code, which simply lacks the feature to add the "current location" marker. If anyone has any input, I'd be thrilled.
var map = null;
var markerArray = [];
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(40.746613, -73.990109),
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
zoomControl: false,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var locations = [
['90 West Apartment', 40.709943, -74.014430, 7, 'images/pin2.png'],
['Caffe Vita', 40.719652, -73.988411, 6, 'images/pin1.png'],
['Croxleys Ale House', 40.722480, -73.983386, 5, 'images/pin1.png'],
['Grays Papaya', 40.778291, -73.981829, 4, 'images/pin2.png'],
['The Back Room', 40.718723, -73.986913, 3, 'images/pin1.png'],
['MUD Coffee', 40.729912, -73.990678, 2, 'images/pin1.png'],
['Nurse Bettie', 40.718820, -73.986863, 1, 'pin2.png']];
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][1], locations[i][2]),locations[i][0], locations[i][3], locations[i][4]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, myTitle, myNum, myIcon) {
var contentString = myTitle;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: myIcon,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title: myTitle
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker);
}
window.onload = initialize;
Let's try this.
Put this in your initialize(): navigator.geolocation.getCurrentPosition(showPosition);
Then define showPosition:
var showPosition = function (position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Do whatever you want with userLatLng.
var marker = new google.maps.Marker({
position: userLatLng,
title: 'Your Location',
map: map
});
}

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

Diplay different Marker in Google Maps API V3 based on PHP value

I have gotten to the point of passing a value from set of Markers created via PHP but I can not figure out how to create or implement the IF condition to show the Marker Image related to the Type value.
Code:
<script type="text/javascript">
var iconStar = new google.maps.MarkerImage("googleMarkers/star.png",
new google.maps.Size(32, 28),
new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var iconBlue = new google.maps.MarkerImage("images/mm_20_blue.png",
new google.maps.Size(12, 20),
new google.maps.Point(0,0),
new google.maps.Point(6, 20));
var iconRed = new google.maps.MarkerImage("images/mm_20_red.png",
new google.maps.Size(12, 20),
new google.maps.Point(6, 20),
new google.maps.Point(5, 1));
var iconYellow = new google.maps.MarkerImage("images/mm_20_yellow.png",
new google.maps.Size(12, 20),
new google.maps.Point(6, 20),
new google.maps.Point(5, 1));
iconType = [] = iconStar;
iconType["0"] = iconStar;
iconType["1"] = iconBlue;
iconType["2"] = iconRed;
iconType["3"] = iconYellow;
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info, type) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: iconType,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
// panTo puts you back to the original center - not good for zoomed in nav
// map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
});
<?php
do {
$name=$row_rsCity['DEALER'];
$lat=$row_rsCity['lat'];
$lon=$row_rsCity['lng'];
$desc=$row_rsCity['ADDRESS'];
$city=$row_rsCity['CITY'];
$state=$row_rsCity['STATE'];
$phone=$row_rsCity['PHONENUMBER'];
$type=$row_rsCity['DEALER_TYPE'];
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc<br/>$city , $state<br />Phone: $phone',$type);\n");
} while ($row_rsCity = mysql_fetch_assoc($rsCity));
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
I'm close but I can't find similar examples online so looking for a little help in solving this issue.
Thanks!
When you call the function addMarker, you need to pass the type of icon (numeric) via the type in your function list.
Then when you are adding the marker. :
function addMarker(lat, lng, info, type) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: iconType[type],
map: map
});
Add in the numeric type to reference the correct icon in your icon array.......
I haven't ever done it this way before but I don't see why it wouldn't work.
If that doesn't work you may want to look at this example. :
Change individual markers in google maps directions api V3
Google Maps API v3: How do I dynamically change the marker icon?

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