More Efficient Way to Add Markers to Google Maps v3 - google-maps-api-3

I am building this JS programmatically. Each marker is being represented by separate variables like marker_0,marker_1, etc... This works but is there a way to generate the markers & info windows in a more efficient/elegant way?
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//**************************************************************
//Add 1st marker
//**************************************************************
var contentString_0 ='<strong>Club name: Fort Wayne Time Corners</strong>';
var infowindow_0 = new google.maps.InfoWindow({
content: contentString_0
});
var image_0 = '/js/markers/marker1.png';
var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
var marker_0 = new google.maps.Marker({
position: Latlng_0,
title:"0",
icon: image_0});
marker_0.setMap(map);
google.maps.event.addListener(marker_0, 'click', function() {
infowindow_0.open(map,marker_0);
});
//**************************************************************
//Add 2nd marker
//**************************************************************
var contentString_1='<strong>Club name: Roanoke</strong>';
var infowindow_1 = new google.maps.InfoWindow({
content: contentString_1
});
var image_1 = '/js/markers/marker2.png';
var Latlng_1 = new google.maps.LatLng(41.17805990,-85.4436640);
var marker_1 = new google.maps.Marker({
position: Latlng_1,
title:"1",
icon: image_1});
marker_1.setMap(map);
google.maps.event.addListener(marker_1, 'click', function() {
infowindow_1.open(map,marker_1);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>

Yes, you can do this easily:
Create an array of data that describes each marker.
Write a function that adds a single marker based on the description in one entry of that array.
Call that function for each entry in that array.
So the only part you have to generate dynamically is that array of data; all of the actual marker code is shared for all markers.
Like this:
var map;
var places = [
{
lat: 41.057814980291,
lng: -85.329851919709,
image: 'marker1',
title: '0',
club: 'Fort Wayne Time Corners'
},
{
lat: 41.17805990,
lng: -85.4436640,
image: 'marker2',
title: '1',
club: 'Roanoke'
}
];
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"),
mapOptions
);
for( var i = 0; i < places.length; i++ ) {
addPlace( places[i] );
}
function addPlace( place ) {
var content = '<strong>Club name: ' + place.club + '</strong>';
var infowindow = new google.maps.InfoWindow({
content: content
});
var image = '/js/markers/' + place.image + '.png';
var latlng = new google.maps.LatLng( place.lat, place.lng );
var marker = new google.maps.Marker({
position: latlng,
title: place.title,
icon: image
});
marker.setMap( map );
google.maps.event.addListener( marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;

Related

Marker cluster displaying only one Marker when having exact corodinates

This is my fiddle
http://jsfiddle.net/6wp7enot/12/
var map = null;
var markerArray = []; //create a global array to store markers
var myPoints = [
[43.65654, -79.90138, 'ABC'],
[43.65654, -79.90138, 'DEF'],
[43.65654, -79.90138, 'GHA']
]; //create global array to store points
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787, -79.359741),
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);
var mcOptions = {
gridSize: 50,
maxZoom: 15
};
var mc = new MarkerClusterer(map, [], mcOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (var i = 0; i < myPoints.length; i++) {
createMarker(new google.maps.LatLng(myPoints[i][0], myPoints[i][1]), myPoints[i][2]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
markerArray.push(marker); //push local var marker into global array
}
window.onload = initialize;
Could you please let me know how to handle this
You created all the three markers at same position means same latitude and longitude. So three markers created at one place only. Please change latitude and longitude of other two elements from the array.
eg.
var myPoints = [
[43.65654, -79.90138, 'ABC'],
[44.65654, -79.90138, 'DEF'],
[45.65654, -79.90138, 'GHA']
]; //create global array to store points

Clustering markers with google maps version 3

I have about 2400 markers that are being displayed on google maps version 3. The problem is that there are too many markers on the map and that is not a good visual representation. What is want to do is group that the markers (i.e. cluster them). I'm experiencing some issues regarding that. Below is my sample code.
function initialize() {
var markers = JSON.parse('<%=ConvertDataTabletoString() %>');
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
//marker:true
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//Get marker image
var redMarker = 'Images/marker2.png';
var greenMarker = 'Images/g48.png';
var currentMarker;
var gmarkers = [];
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var mag = data.Magnitude;
if (mag < 5) {
currentMarker = greenMarker;
}
else if (mag >= 5) {
currentMarker = redMarker;
};
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
icon: currentMarker
});
(function (marker, data) {
//Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent('Magnitude: ' + data.Magnitude + '<br />'
+ 'Location: ' + data.title);
infoWindow.open(map, marker);
});
})(marker, data);
gmarkers.push(marker);
}
}
var markerCluster = new MarkerClusterer(map, gmarkers);
window.onload = function () { initialize();
}
I get a javascript error in your code as posted
Uncaught ReferenceError: map is not defined
on this line:
var markerCluster = new MarkerClusterer(map, gmarkers);
The map variable is local to the initialize function.
That line is outside of the initialize function, so the map variable isn't available to it.
Put it inside the initialize function (but after the markers have been parsed).

Adding Google maps InfoWindow Dynamically Wordpress

I am trying to add a Google maps InfoWindow Dynamically to Wordpress, this is the code that is currently working with a custom marker I have tried several functions for infowindows but it seems to be breaking and not loading the map. not sure what I might be doing wrong.
this works I just need to add a infoWindow
<script type="text/javascript">
//<![CDATA[
function load() {
var styles =
[
{
"stylers": [
{ "lightness": 1 },
{ "saturation": -76 },
{ "hue": "#3bff00" }
]
}
];
var lat = <?php echo $lat; ?>;
var lng = <?php echo $lng; ?>;
// coordinates to latLng
var latlng = new google.maps.LatLng(lat, lng);
// map Options
var myOptions = {
zoom: 14,
scrollwheel: false,
center: latlng,
mapTypeId: 'Styled'
};
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
map.mapTypes.set('Styled', styledMapType);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: '/wp-content/themes/bills_theme/images/pin_bills.png',
});
}
// call the function
load();
//]]>
</script>
A simple infowindow would be (not tested):
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
map.mapTypes.set('Styled', styledMapType);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: '/wp-content/themes/bills_theme/images/pin_bills.png',
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("Hello world");
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, "click");
}
// call the function
Just add this code:
var contentString = 'put your content here.';
google.maps.event.addListener(marker, 'click', function() {
var infowindow = new google.maps.InfoWindow({
content: contentString,
position: latlng,
maxWidth: 200
});
infowindow.open(map);
});
More info about Info Window you can read HERE.

Google Map Marker not being replaced

please excuse a noob at this. When a user clicks on a map, it should place a marker and open an info window - as per this example: http://www.geocodezip.com/v3_example_click2add_infowindow.html
The code below almost works correctly, except that the mark is not replaced - a new one is added. Any ideas really, really gratefully received. Thank you.
<script>
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var marker , i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
This is a scope issue. You are always delcaring marker in the placeMarker function so if( marker ) will always be false. Move the variable declaration out of that function:
<script>
var marker;
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
Your placeMarker function creates a new (empty) marker variable in the local scope.
function placeMarker(location) {
var marker , i ;
if ( marker ) {
It will always create a new marker. Change it to:
var marker = null;
function placeMarker(location) {
if ( marker ) {

update infowindows when calling again a xml file

Good morning.
I have the next code which put some markers in a map from a xml file, every 5 seconds I call again the xml file and I update the position of the markers, but the problem is that the infowindows are not updated. Does anyone knows how to update them=
Here you have the code:
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
map.setZoom(map.getZoom()+2);
}
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();
});
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 altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" "+speed+" km/h <br/> "+timestamp;
var marker = createMarker(point,alias+" "+imei,html,estado,alias, speed, timestamp, altitude, angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,60)
});
setInterval(function updateMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
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 altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" a "+speed+" km/h <br/> "+timestamp;
var newLatLng = gmarkers[i].setPosition(point,alias+" "+imei,html,estado,alias,speed,timestamp,altitude,angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}, 5000);
//finish updateMarkers
function createMarker(latlng, imei, html, estado, alias, speed, timestamp, altitude, angle) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= alias+" speed: "+ speed+" km/h";
var contentString = html;
var newLatLng = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
draggable: true,
flat: true,
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(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
});
gmarkers.push(newLatLng);
// side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei +'<\/a><br>';
}
You are not assigning the event handler in the setInterval function, so no infowindows.
Add this code to the setInterval() after creating the marker
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
This may result in a closure problem as you are in a loop. So you can do something like the solutions in this Passing values in for loop to event listeners- Javascript.

Resources