Marker cluster displaying only one Marker when having exact corodinates - google-maps-api-3

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

Related

More Efficient Way to Add Markers to Google Maps v3

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;

Google maps v3 geocode multiple custom markers by address or latlng

I need to plot multiple custom map markers using MapsV3 api either by an address or lat/lon. I put together the following code which works ok for lon/lat, but if the data contains an address the geocoder returns nothing. Any ideas on how to fix this.
$(document).ready(function () { initialize(); });
function initialize() {
var centerMap = new google.maps.LatLng(-27.0,133.0);
var options = {
panControl: false,
zoomControl: true,
scaleControl: false,
mapTypeControl: false,
streetViewControl: false,
zoom: 3,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var data = [
{
'title':'F C Building Construction ...',
'address':'',
'zindex':20,
'lat':'-33.797847',
'lon':'151.259928',
'marker_number':1,
'marker_html':' html content...',
'image': {
url:'//localhost/assets/images/markers/marker_1.png',
size: new google.maps.Size(24, 29),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(10, 29)
}
}];
setMarkers(map, data);
var infowindow = new google.maps.InfoWindow();
}
function showMapPin(i) { }
function setMarkers(map,data) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
setMarker(map, data[i], bounds);
}
map.fitBounds(bounds);
}
function setMarker(map, m, bounds) {
if(m["address"]!="") {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": m["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var siteLatLng = results[0].geometry.location;
}
});
} else {
var siteLatLng = new google.maps.LatLng(m["lat"], m["lon"]);
}
if(siteLatLng) {
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
//shadow: shadow,
icon: m["image"],
title: m["title"],
zIndex: m["zindex"],
html: m["marker_html"]
});
bounds.extend(siteLatLng);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} // if latlng
}//]]>
After looking back over the code I realized that the variable siteLatLng is within geocode function scope so it never gets passed and it can't be returned. Setting the marker within this function works.

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

I can't add multiple markers in Google Map API v3

Hi,
that's normal code at Google
var map;
function initialize()
{
var latLng = new google.maps.LatLng(41.079120183660486, 28.994637246032653);
var mapOptions = {
center: latLng,
zoom: 8,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
});
google.maps.event.addListener(map, 'click', function (event) {
//map.setZoom(9);
//map.setCenter(marker.getPosition());
});
}google.maps.event.addDomListener(window, 'load', initialize);
and I want to multiply marker from my DB and I can't do it. I searched in site but always result is gray map.
And my code is:
<script type="text/javascript">
var map;
var latLng;
function initialize() {
var mapOptions = {
//center: latLng,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var markers = [];
#foreach (var item in Model)
{
#:markers.push("#item.map")
// item.map content coming like this : 41.079120183660486,28.994637246032653
}
for (var i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
});
}
//google.maps.event.addListener(map, 'click', function (event) {
// //map.setZoom(9);
// map.setCenter(marker.getPosition());
// //placeMarker(event.latLng);
//});
}
google.maps.event.addDomListener(window, 'load', initialize);
I can't add markers. I think missing a lot of things? I really need your opinion. Thanks
Based on your code, it looks like you're adding markers to the same lat/lng. The code below adds a few markers in a loop.
<script>
var map;
var center = new google.maps.LatLng(39.715, -84.103);
$(document).ready(initialize);
function initialize() {
// Create map
var mapOptions = {
zoom: 10,
center: center,
panControl: false,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map_canvas')[0], mapOptions);
for (var ii = 0; ii < 5; ii++) {
var lat = center.lat() + (0.1 * ii);
var lng = center.lng() + (0.1 * ii);
var loc = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: loc,
map: map
});
}
}
</script>

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