google maps API v3 - zoom after load How - google-maps-api-3

I am trying to get google maps to load, then zoom into my marker, but I have something wrong with my javascript, as the scope of the map is not visible, despite it being defined globally.
Any ideas what I am doing wrong ?
Many thanks
Mark
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="js/jquery-1.10.1.min.js"></script>
<link href="css/default.css" rel="stylesheet">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: https://developers.google.com/apis/maps/documentation/javascript/basics#SpecifyingSensor
-->
<script src="https://maps.googleapis.com/maps/api/js?v=3.12&sensor=true"></script>
<script>
//START Global Variables
var geocoder;
var map;
var marker;
var initialZoomLevel = 7;
var endZoomLevel = 16;
var zoomTimeInterval_ms = 1000;
var mapIcon = {
url: "images/im_here.png",
// This marker is 130 pixels wide by 120 pixels tall
size: new google.maps.Size(130,120),
//scale image so it works with retina displays
scaledSize: new google.maps.Size(65,60),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor point is be middle of the base
anchor: new google.maps.Point(32.5,60)
};
var mapIcon_shadow = {
url: "images/im_here_shadow.png",
// This shadow is 191 pixels wide by 120 pixels tall
size: new google.maps.Size(191,120),
//scale image so it works with retina displays
scaledSize: new google.maps.Size(95.5,60),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor point is be middle of the base
anchor: new google.maps.Point(32.5,60)
};
//Enable the visual refresh
google.maps.visualRefresh = true;
//END Global Variables
/** Initialise function to render the map */
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: initialZoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false
};
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);
// set home location
home = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// the marker where you are
marker = new google.maps.Marker({
map: map,
position: pos,
icon: mapIcon,
shadow: mapIcon_shadow,
draggable: true
});
codeLatLng(pos);
map.panTo(pos);
google.maps.event.addListener(marker, 'dragend', function(a) {
//alert('LatLng is '+a.latLng.lat()+ " "+ a.latLng.lng());
codeLatLng(a.latLng);
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
// Create the DIV to hold the control and
// call the HomeControl() constructor passing
// in this DIV.
//var homeControlDiv = document.createElement('div');
//var homeControl = new HomeControl(homeControlDiv, map);
//homeControlDiv.index = 1;
//map.controls[google.maps.ControlPosition.TOP_CENTER].push(homeControlDiv);
smoothZoom(map, endZoomLevel, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
}
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
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function codeLatLng(markerLatLang) {
//var latlng = new google.maps.LatLng(latLng.lat(), latLng.lng());
geocoder.geocode({'latLng': markerLatLang}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
name = results[0].formatted_address;
latlongStr = "LAT = ["+markerLatLang.lat()+"] LNG = ["+markerLatLang.lng()+"]";
//alert("name = "+name);
$('#address').html(name);
$('#latlong').html(latlongStr);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
/**
* The HomeControl adds a control to the map that simply
* returns the user to home. This constructor takes
* the control DIV as an argument.
* #constructor
*/
/** TODO need to rewite this as normal div, not on map **/
function HomeControl(controlDiv, map) {
// Set CSS styles for the DIV containing the control
// Setting padding to 5 px will offset the control
// from the edge of the map
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Start Location';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Helvetica,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.style.zIndex = "100";
controlText.innerHTML = '<b>Reset Map</b>';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map back to home
google.maps.event.addDomListener(controlUI, 'click', function() {
marker.setPosition(home);
map.setCenter(home);
});
}
// the smooth zoom function
function smoothZoom (map, max, cnt) {
if (cnt >= max) {
return;
}
else {
z = google.maps.event.addListener(map, 'zoom_changed', function(event){
google.maps.event.removeListener(z);
self.smoothZoom(map, max, cnt + 1);
});
setTimeout(function(){map.setZoom(cnt)}, zoomTimeInterval_ms);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<div id="latlong">No latlong Yet</div>
<div id="address">No Address Yet</div>
</div>
<div id="map-canvas"></div>
</body>
</html>

The fact that your map is defined globally isn't relevant if you don't wait until it is initialized before using it.
It is initialized by the initialize function which runs on the body onload event. You use it inline before that happens. This works for me:
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: initialZoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
google.maps.event.addListenerOnce(map,"zoom_changed", function() {
smoothZoom(map, endZoomLevel, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
});
working example
seems the zoom_changed event doesn't fire when the map initializes, using the "idle" event seems to work:
working example with zoom on idle

Related

Google map showing grey bands and looks distorted

For some reason, even though my Google map is showing, there are strange grey bands/lines running through the map (image link below).
Just for reference it uses the places API to search for locations.
Screenshot of the map issue
Anybody have any ideas why this might be? Here's the code for the map:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
<script type="text/javascript">
function search_map_init() {
var args = {
disableDefaultUI : true,
center : new google.maps.LatLng(51.6948168, -0.6433884),
mapTypeId : google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
zoom : 12,
styles : [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}]
};
var map = new google.maps.Map(document.getElementById('map-canvas'), args);
var marker_url = {
url : 'IMG_URL',
scaledSize : new google.maps.Size(48, 65)
};
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location,
icon : marker_url
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
var new_address = $('#pac-input').val();
var new_lat = place.geometry.location.lat();
var new_lng = place.geometry.location.lng();
$('input[name="post[meta_input][map][address]"]').val(new_address);
$('input[name="post[meta_input][map][lat]"]').val(new_lat);
$('input[name="post[meta_input][map][lng]"]').val(new_lng);
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
return map;
}
google.maps.event.addDomListener(window, 'load', search_map_init);
</script>
Note: I've replaced the API key and image URL with API_KEY and IMG_URL in the code above.
I was setting min-width in the CSS for something else which was also effecting the map display. Problem solved!

Show data when Google Maps marker is clicked in markercluster

I am trying to work out how to show custom data when a Google Maps markerclusterer marker is clicked but can't find this documented anywhere.
My markerclusterer code looks like this but my attempt at capturing the click event on a marker is not working:
var markerClusterer = null;
var map = null;
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' +
'chco=FFFFFF,008CFF,000000&ext=.png';
google.maps.event.addDomListener(window, 'load', initialize);
function refreshMap() {
if (markerClusterer) {
markerClusterer.clearMarkers();
}
var markers = [];
var markerImage = new google.maps.MarkerImage(imageUrl,
new google.maps.Size(24, 32));
/*
for (var i = 0; i < 1000; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude)
var marker = new google.maps.Marker({
position: latLng,
icon: markerImage
});
markers.push(marker);
}
*/
for (var i = 0; i < numItemsToShow; ++i) {
var latLng = new google.maps.LatLng(itemsToShow[i].lat, itemsToShow[i].long);
var marker = new google.maps.Marker({
position: latLng,
icon: markerImage
});
markers.push(marker);
}
var zoom = parseInt(document.getElementById('zoom').value, 10);
var size = parseInt(document.getElementById('size').value, 10);
var style = parseInt(document.getElementById('style').value, 10);
zoom = zoom == -1 ? null : zoom;
size = size == -1 ? null : size;
style = style == -1 ? null: style;
markerClusterer = new MarkerClusterer(map, markers, {
maxZoom: zoom,
gridSize: size,
styles: styles[style]
});
}
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(39.91, 116.38),
mapTypeId: google.maps.MapTypeId.ROADMAP,
//styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"administrative.land_parcel","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape.natural","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"on"},{"color":"#052366"},{"saturation":"-70"},{"lightness":"85"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"saturation":"-100"},{"lightness":"0"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"simplified"},{"lightness":"-53"},{"weight":"1.00"},{"gamma":"0.98"}]},{"featureType":"poi","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.icon","stylers":[{"visibility":"off"},{"lightness":"0"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"hue":"#3dff00"},{"saturation":"-100"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45},{"visibility":"on"}]},{"featureType":"road","elementType":"geometry","stylers":[{"saturation":"-18"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"road.local","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"road.local","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#57677a"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"lightness":"40"}]}]
styles: [{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#b5cbe4"}]},
{"featureType":"landscape","stylers":[{"color":"#efefef"}]},
{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#83a5b0"}]},
{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#bdcdd3"}]},
{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"}]},
{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#e3eed3"}]},
{"featureType":"administrative","stylers":[{"visibility":"on"},{"lightness":33}]},
{"featureType":"road"},
{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{},
{"featureType":"road","stylers":[{"lightness":20}]}]
});
var refresh = document.getElementById('refresh');
google.maps.event.addDomListener(refresh, 'click', refreshMap);
var clear = document.getElementById('clear');
google.maps.event.addDomListener(clear, 'click', clearClusters);
google.maps.event.addListener(markerClusterer, 'click', function () {
// do something with this marker ...
this.setTitle('I am clicked');
});
refreshMap();
}
function clearClusters(e) {
e.preventDefault();
e.stopPropagation();
markerClusterer.clearMarkers();
}
This works for me (it opens an infowindow when you mouseover the cluster icon, if you click on the cluster icon, the default behavior is to zoom to the cluster bounds, which makes it hard to see the change of the tooltip/title on the cluster icon):
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(markerClusterer, 'mouseover', function (cluster) {
// do something with this cluster ...
infoWindow.setContent("Mouseover<br>"+cluster.getCenter().toUrlValue());
infoWindow.setPosition(cluster.getCenter());
infoWindow.open(map);
});

Google Maps API 3 - Type error: a is undefined

I'm attempting to dynamically load geocodes from a json file here http://debug-gotfed.admin.zope.net/bataviaeats/at/dev_remote_content
I'm getting a "Type Error: a is undefined." What am I missing?
<script type="text/javascript">
// Global
var infowindow;
var markers_img = 'http://gotfed.in/!/assets/global_images/got-fed-in-marker.png';
var infoCloseIcon = 'images/close.png';
var infoCloseMargin = '4px 4px 2px 2px';
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(58, 16),
scrollwheel: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$.each(locations, function(i, data) {
console.log(data.geocode);
var position = new google.maps.LatLng(data.geocode);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: markers_img
});
console.log(marker);
// marker.setMap(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You are either having the firebug console open when loading the page or one of firefox extension clogging the downloading, making the browser can not get full script from google.
Solution: turn of firebug console, if that's not the case, then try disable the extensions individually see what conflict.
Just add the v3 for example as release version ,and it will work with firebug and any other extension
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
all credits goes here :
Google Maps API: TypeError: a is undefined
The google.maps.LatLng constructor takes two arguments. This is wrong:
var position = new google.maps.LatLng(data.geocode);
If data.geocode is already a google.maps.LatLng object, just use it. If it is a JSON object with lat and lng properties, then you have to pass those separately into the constructor:
var position = new google.maps.LatLng(data.geocode.lat, data.geocode.lng);
code for your specific data:
var geocode=data.geocode.split(',');
var position = new google.maps.LatLng(geocode[0],geocode[1]);
Thank you to all who answered. This is the final working code with additions for Infoboxes. I did have to turn the split geocode data into numbers. You can view this in real-time # http://gotfed.in/fredericksburg-va
<script type="text/javascript">
// Global
var map;
var infowindow;
var markers_img = 'http://gotfed.in/!/assets/global_images/got-fed-in-marker.png';
var infoCloseIcon = 'http://gotfed.in/!/assets/global_images/close.png';
var infoCloseMargin = '4px 4px 2px 2px';
bounds = new google.maps.LatLngBounds();
function initialize() {
var mapOptions = {
scrollwheel: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// create markers
$.each(locations, function(i, data) {
var geocode = data.geocode.split(',');
var geo1 = parseFloat(geocode[0]);
var geo2 = parseFloat(geocode[1]);
var position = new google.maps.LatLng(geo1,geo2);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: markers_img,
title: data.business_name
});
bounds.extend(position);
var id = "info" + i;
console.log(id);
var infobox = new InfoBox({
content: document.getElementById(id),
disableAutoPan: false,
maxWidth: 150,
pixelOffset: new google.maps.Size(-140, 0),
zIndex: null,
boxStyle: {width: "280px"},
closeBoxMargin: infoCloseMargin,
closeBoxURL: infoCloseIcon,
infoBoxClearance: new google.maps.Size(1, 1)
});
google.maps.event.addListener(marker, 'click', function() {
infobox.open(map, this);
map.panTo(position);
});
});
// set Bounds
map.fitBounds(bounds);
// Keep map centered
var center;
function calculateCenter() {
center = map.getCenter()
}
google.maps.event.addDomListener(map, 'idle', function() {
calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(center);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

maps.event.trigger Resize( ) not working

I am working on google maps for quite some time, I am familiar with code and how it works, but unable to place the resize event properly that causes my map to render grey tiles on screen.
Please suggest me where exactly need to place the resize event
Here is my code :
bank.atmDetailsSuccess = function(response) {
bank.locate = response;
bank.getAtmStatus();
};
bank.getAtmStatus = function(results, status) {
var status = bank.locate.Status[0].Value0;
locate = bank.locate;
var map;
if (status == bank.constants.STATUS_ERROR) {
var message = locate.Error[0].Value0;
WL.simpledialog.show(message);
} else if (status == bank.constants.STATUS_SESSION_EXPIRED) {
WL.simpledialog.show("Session Expired!!");
} else if (status == bank.constants.STATUS_SUCCESS) {
map = bank.initializeAtm();
google.maps.event.addDomListener(window, 'load', initializeAtm);
google.maps.event.addDomListener(window, "resize", function() {
alert("In");
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.setZoom(10);
});
}
};
bank.initializeAtm = function(){
locate = bank.locate;
var firstlat = locate.Stmt[0].Value5;
var firstlong= locate.Stmt[0].Value6;
// var latlng = new google.maps.LatLng(latitude,longitude);
var image = {
//url: bank.constants.MARKER_PATH,
url: 'images/720x720/pin.png',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(32, 40),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 32)
};
var myOptions = {
zoom: 10,
center:new google.maps.LatLng(firstlat, firstlong),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map-canvas')[0], myOptions);
geocoder = new google.maps.Geocoder();
bank.currentposition();
$('#mapbranch').hide();
$('#map-canvas').show();
$('#atm').html("ATM near your current location");
$('#results').html("");
var directionsService = new google.maps.DirectionsService();
MVC.local.directService = directionsService;
directionsRenderer = new google.maps.DirectionsRenderer({
suppressMarkers: true} );
MVC.local.renderer = directionsRenderer;
var n;
for(n=0; n<locate.Stmt.length; n++)
{
var value = locate.Stmt[n];
name = value.Value0,value.Value1;
lat = value.Value5;
lon = value.Value6;
bank.getDistanceFromLatLonInKm(12.919336, 77.502291,lat,lon);
var myLatLng = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker({
position: myLatLng,
icon:image,
map: map,
title: name,
zIndex: 1
});
bank.buildInfoWindow(marker,map,value[n]);
}
return map;
};
Note:This is completely working code only problem is rendering works when i resize broswer manually but not resizing while loading. Please don't mind variable names.All function calls are good except resize event.

duplicated markers when calling a function using setinterval google maps v3

I have the next code to retrieve some data from a xml file. The problem is that when I want to refresh the markers, the response that I get is a duplicated marker in the map. How can I update the points without having duplicated markers?
Best regards
//<![CDATA[
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// global "map" variable
var map = null;
var markerclusterer = null;
// A function to create the marker and set up the event window function
function createMarker(latlng, imei, html, estado, alias, speed, timestamp) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= "this is the text"
var contentString = html;
var marker = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
labelContent: textoLabel,
labelAnchor: new google.maps.Point(40, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.50},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(37.169619,-3.756981),
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);
}
function getMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var html="<b>"+alias+"</b><br> a una velocidad de "+speed+" km/h <br/> ultima posicion a las: "+timestamp;
// create the marker
var marker = createMarker(point,alias+" "+imei,html,estado, speed, timestamp );
}
markerCluster = new MarkerClusterer(map, gmarkers);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// Removes the overlays from the map, but keeps them in the array.
function clearOverlays() {
getMarkers(null);
}
// Deletes all markers in the array by removing references to them.
function deleteOverlays() {
clearOverlays();
getMarkers = [];
}
setInterval(clearOverlays, 3000);
setInterval(deleteOverlays, 4000);
setInterval(getMarkers, 5000);
Give your markers unique ids (maybe one of your existing attributes is already unique). If the unique id already exists, move that marker to the new location (or just don't add it again),if it doesn't, create a new marker.
If they don't move, you can also avoid duplicates by checking the distance between new markers and all your existing markers, if it is less than a "same marker" threshold (say ~0.1 meters), don't add it again.
There is a problem with your clearOverlays method (getMarkers(null) just calls getMarkers):
// Removes the overlays from the map, but keeps them in the array.
function clearOverlays() {
for (var i=0; i<gmarkers.length; i++)
{
gmarkers[i].setMap(null);
}
}

Resources