Google Maps V3- Place marker and polyline with interval - javascript

I have been trying for hours and also referred to a post in this forum but failed. I have a large number of markers, up to 1000 markers on the map. It slows down my map when I try to move the map's position. So I need to set an interval of markers to be shown on the map. Let's say with interval of 10 when there are more than 300 markers. How can I do that? Below is my code :
var trace_markers= [];
var pins = [];
var pin;
function Trace_Pin(Lat, Long, immat, type, site, vitesse, date){
pin = {
latitude: document.getElementById('Lat'),
longitude: document.getElementById('Long'),
immat: document.getElementById('immat'),
date: document.getElementById('date'),
type: document.getElementById('type'),
site: document.getElementById('site'),
speed: document.getElementById('vitesse')
};
pins.push(pin);
ListPin();}
function ListPin()
{
var image_trace = new google.maps.MarkerImage('http://maps.google.com/mapfiles/kml/pal3/icon61.png',
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(16, 16));
if (pins.length > 200){
for ( var i=0; i< pins.length ;i+10){
var vehlatlng = new google.maps.LatLng(pins[i].latitude, pins[i].longitude) ;
var trace_marker = new google.maps.Marker({
map: map,
position: vehlatlng,
icon: image_trace });
trace_marker.tooltip_html = '<div class="tooltip">' + 'Date : ' + pins[i].date + '<br>' + 'Vitesse : ' + pins[i].vitesse + ' km/h' + '<br>' + '<\/div>';
trace_markers.push(trace_marker);
trace_marker.setMap(map);
Liste_Points.push(trace_marker.getPosition());
TraceBounds.extend(trace_marker.position); }
}
if (pins.length < 200){
for ( var i=0;i< pins.length ;i++){
var vehlatlng = new google.maps.LatLng(pins[i].latitude, pins[i].longitude) ;
var trace_marker = new google.maps.Marker({
map: map,
position: vehlatlng,
icon: image_trace });
trace_marker.tooltip_html = '<div class="tooltip">' + 'Date : ' + pins[i].date + '<br>' + 'Vitesse : ' + pins[i].vitesse + ' km/h' + '<br>' + '<\/div>';
trace_markers.push(trace_marker);
trace_marker.setMap(map);
Liste_Points.push(trace_marker.getPosition());
TraceBounds.extend(trace_marker.position); }
}
// Evenement MouseOver
//-----------------------------------------------------
google.maps.event.addListener(map, 'mouseover', function() {
showTooltip(trace_marker);
});
}
// ------------------------------------------------------------------------------------
//**************************************************************************************
// On joint les points du parcours
//**************************************************************************************
// ------------------------------------------------------------------------------------
function Trace_Route() {
if (route) { route.setMap(null); }
if (Liste_Points.length > 1) {
route = new google.maps.Polyline({
path: Liste_Points,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2});
route.setMap(map);
}
}

Create an array where you have all your markers (300 of them).
Lets assume that is called
allMarkersArray[]
When you create a marker you do not set the map, but you leave it null so it won't be shown on the map. When you want to show the markers you do some math. Lets say that you want to show only the 1/30 (10 out of 300) of the markers. You create another array
shownMarketsArray[]
where you place the markers you want to show and when you put them there you set the map
marker.setMap(map)
Now the criteria of which markers will be shown, and which markers will remain hidden are up to you. If you want the 1/30 of the markers just have a for loop
for(var i = 0; i < allMarketsArray.length/30; i++)
You should take some precautions though (i.e. the array is too small and you want to show all of them).
UPDATE
if (pins.length > 200){
for ( var i=0; i< pins.length ;i+10){
var vehlatlng = new google.maps.LatLng(pins[i].lat, pins[i].long) ;
var trace_marker = new google.maps.Marker({
map: map,
position: vehlatlng,
icon: image_trace });
trace_marker.tooltip_html = '<div class="tooltip">' + 'Date : ' + pins[i].date + '<br>' + 'Vitesse : ' + pins[i].vitesse + ' km/h' + '<br>' + '<\/div>';
trace_markers.push(trace_marker);
trace_marker[i].setMap(map);
Liste_Points.push(trace_marker.getPosition());
TraceBounds.extend(trace_marker.position); }
}
if (pins.length < 200){
for ( var i=0;i< pins.length ;i++){
var vehlatlng = new google.maps.LatLng(pins[i].lat, pins[i].long) ;
var trace_marker = new google.maps.Marker({
map: map,
position: vehlatlng,
icon: image_trace });
trace_marker.tooltip_html = '<div class="tooltip">' + 'Date : ' + pins[i].date + '<br>' + 'Vitesse : ' + pins[i].vitesse + ' km/h' + '<br>' + '<\/div>';
trace_markers.push(trace_marker);
trace_marker[i].setMap(map);
Liste_Points.push(trace_marker.getPosition());
TraceBounds.extend(trace_marker.position); }
}

Related

Trying to add button in googlemap infoWindow

I'm trying to add a button in googlemap infoWindow but I'm beginner in javascript and I have spent weeks on this and still not working... So I hope one of you will be able to help me.
To explain you a litle bit... I get markers from a bdd to display them on a map. Then on marker click, a infoWindow opens with all info marker on it.
This is all working perfectly but then is when I don't get it.
I have added a submit button to each infoWindow markers and I would like an action on submit button click (save to database). But the button is not responding at all...
I removed all the code containing the save function to keep it all clear as there is a alert("click") to test the button...
<script type="text/javascript">
var bounds;
var markers = [];
var markerCount = 0;
function initialize(){
bounds = new google.maps.LatLngBounds();
var myLatLng = new google.maps.LatLng(46.775090, 2.507969);
var mapOptions={
zoom: 6,
center: myLatLng,
maxZoom: 11,
},
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(map,marker);
const geocoder = new google.maps.Geocoder();
document.getElementById("submit").addEventListener("click", () => {
geocodeAddress(geocoder, map);
});
}
function setMarkers(map,locations){
for(var i=0; i<locations.length; i++){
var station = locations[i];
var myLatLng = new google.maps.LatLng(station['marker_latitude'], station['marker_longitude']);
var infoWindow = new google.maps.InfoWindow();
var image = 'https://marchad.fr/wp-includes/images/marchad.png';
var description = station['marker_text'];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: station['marker_ville'],
id: station['marker_id']
});
(function(marker, i){
google.maps.event.addListener(marker, "click",function(){
var station = locations[i];
var mId = station['marker_id']; //description input field value
var contentString = ("<div id='infoWindow"+station['marker_id']+">"
+"<p class='texte'><strong>"+station['marker_text']+"</strong><p>"
+"<p class='texte'>Ce staliad est géré par un "+station['marker_user_type']+"<p>"
+"<p class='texte'><strong>Adresse : </strong>"+station['marker_adresse']+"<p>"
+"<p class='texte'><strong>Jour de permanence : </strong>"+station['marker_day']+"<p>"
+"<p class='texte'><strong>Dépôts : </strong>de "+station['marker_depot_start_time']+" à "+station['marker_depot_end_time']+"<p>"
+"<p class='texte'><strong>Retraits : </strong>de "+station['marker_start_time']+" à "+station['marker_end_time']+"<p>"
+"<p class='texte'><strong>Téléphone : </strong>"+station['marker_user_contact']+"<p>"
+"<p class='texte'><strong>Mail : </strong>"+station['marker_contact_mail']+"<p>"
+"<p class='texte'><strong>Commentaire : </strong>"+station['marker_commentaire']+"<p>"
+'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker'+station['marker_id']+'">'
+'<input id="idInput'+station['marker_id']+'" type="hidden" name="marker-id" class="marker-id'+station['marker_id']+'" value='+station['marker_id']+' />'+station['marker_id']+'</input>'
+'</form>'
+'<input id="inputButton'+station['marker_id']+'" type="button" id="save-marker'+station['marker_id']+'" name="save-marker" class="save-marker'+station['marker_id']+'" data-id="'+station['marker_id']+'" value="M\'inscrire" />'
+'<div id="test'+station['marker_id']+'">'+vendorId+'</div>'
+'<span class="info-content'+station['marker_id']+'">'
+'<h1 class="marker-heading"></h1>'
+'</span>'
+"</div>"
);
infoWindow.close();
infoWindow.setContent(contentString);
infoWindow.open(map,this);
var class_name_removeBtn = 'remove-marker'+station['marker_id'];
var class_name_saveBtn = 'save-marker'+station['marker_id'];
var removeBtn = document.getElementsByClassName(class_name_removeBtn);
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
console.log(removeBtn);
console.log(saveBtn);
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function(event) {
var class_name_mReplace = 'info-content'+station['marker_id'];
var class_name_mName = 'marker-id'+station['marker_id'];
var mReplace = document.getElementsByClassName(class_name_mReplace); //html to be replaced after success
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var mId = station['marker_id'];
var vId = vendorId;
console.log(mReplace);
console.log(mName);
console.log(mId);
console.log(vId);
if(mId !=='')
{
alert("click");
save_marker( mName, mId, mReplace,vId); //call save marker function
}else{
alert("Something went wrong. Please contact admin");
}
});
if(typeof removeBtn !== 'undefined') //continue only when save button is present
{
google.maps.event.addDomListener(removeBtn, "click", function(event) {
var class_name_mName = 'marker-id'+station['marker_id'];
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var vId = vendorId;
remove_marker(mName,vId);
});
}
});
})(marker, i);
}
}
</script>
Your first problem is the saveBtn is not part of the DOM until the InfoWindow has been opened as you are adding as a string in the InfoWindow content.
Relate questions:
using addDomListener with googlemaps not working
Turn off google map's infowindow.open(map) asynchronous behaviour
Adding Event Listener on button - Javascript
The second problem is that document.getElementsByClassName(class_name_saveBtn); returns an array. Instead of:
document.getElementsByClassName(class_name_saveBtn);
for a single marker, you need:
document.getElementsByClassName(class_name_saveBtn)[0];
for multiple markers/infowindows (get the last one created):
var removeBtn = document.getElementsByClassName(class_name_removeBtn);
removeBtn = removeBtn[removeBtn.length-1];
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
saveBtn = saveBtn[saveBtn.length-1];
proof of concept fiddle
code snippet:
var bounds;
var markers = [];
var markerCount = 0;
/* var marker = [{
marker_latitude: 47.394144,
marker_longitude: 0.68484,
marker_id: 1
}] */
var marker = [{"marker_id":"6","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"5","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.434917","marker_latitude":"43.573085","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Casino Barri\u00e8re","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"7","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.447856","marker_latitude":"43.604573","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Gaumont Wilson","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"8","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Lab\u00e8ge","marker_departement":"31","marker_region":"0","marker_longitude":"1.511496","marker_latitude":"43.53992","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Gaumont Lab\u00e8ge","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"9","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Blagnac","marker_departement":"31","marker_region":"0","marker_longitude":"1.373341","marker_latitude":"43.644029","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Mega CGR Blagnac","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"10","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.435198","marker_latitude":"43.62186","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Minimes\r\n108 Bis Avenue des Minimes, 31200 Toulouse \u200e\r\n05 61 47 95 60","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"11","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Montaudran","marker_departement":"31","marker_region":"0","marker_longitude":"1.496152","marker_latitude":"43.568863","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Montaudran Impasse Louise Lab\u00e9 31400 Toulouse 05 61 20 20 70","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"12","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Colomiers","marker_departement":"31","marker_region":"0","marker_longitude":"1.304691","marker_latitude":"43.609902","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Stadium Colomiers\r\n29 Chemin du Loudet\r\n33770 Colomiers\r\n05 34 36 42 50","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"13","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"10","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Plaisance-du-Touch","marker_departement":"31","marker_region":"0","marker_longitude":"1.260248","marker_latitude":"43.55854","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"African Safari\r\n41 Rue des Landes\r\n31830 Plaisance-du-Touch\r\n05 61 86 45 03","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"29","marker_user_id":"2","marker_user_type":"marchand","marker_user_stal":"Aux petits l\u00e9gumes","marker_categorie":"test","marker_adresse":"12 Rue du Bocage, Tr\u00e9gueux, France","marker_numero_voie":"12","marker_voie":"Rue du Bocage","marker_zip":"22950","marker_ville":"Tr\u00e9gueux","marker_departement":"C\u00f4tes-d'Armor","marker_region":"Bretagne","marker_longitude":"-2.7515737","marker_latitude":"48.4831891","marker_day":"Lundi","marker_depot_start_time":"09:00:00","marker_depot_end_time":"12:00:00","marker_start_time":"12:00:00","marker_end_time":"18:46:00","marker_text":"Aux petits l\u00e9gumes","marker_user_contact":"0783312456","marker_contact_mail":"nattydreadnatty#live.fr","marker_enable_contact_telephone":"yes","marker_enable_contact_mail":"yes","marker_commentaire":"test test test test test testing out","marker_actif":"oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"30","marker_user_id":"3","marker_user_type":"marchand","marker_user_stal":"Poivrons et compagnie","marker_categorie":"","marker_adresse":"12t Rue du Vau Hello, 22360 Langueux, France","marker_numero_voie":"12","marker_voie":"Rue du Vau Hello","marker_zip":"22360","marker_ville":"Langueux","marker_departement":"C\u00f4tes-d'Armor","marker_region":"Bretagne","marker_longitude":"-2.7262882","marker_latitude":"48.50448799999999","marker_day":"Vendredi","marker_depot_start_time":"08:00:00","marker_depot_end_time":"10:00:00","marker_start_time":"10:00:00","marker_end_time":"18:00:00","marker_text":"Poivrons et compagnie","marker_user_contact":"","marker_contact_mail":"lucbinard4#gmail.com","marker_enable_contact_telephone":"yes","marker_enable_contact_mail":"yes","marker_commentaire":"","marker_actif":"oui","id":null,"mark_id":null,"user_id":null,"user_actif":null}];
var vendorId = "vendorId";
function initialize() {
bounds = new google.maps.LatLngBounds();
var myLatLng = new google.maps.LatLng(46.775090, 2.507969);
var mapOptions = {
zoom: 6,
center: myLatLng,
maxZoom: 11,
},
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(map, marker);
const geocoder = new google.maps.Geocoder();
document.getElementById("submit").addEventListener("click", () => {
geocodeAddress(geocoder, map);
});
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var station = locations[i];
var myLatLng = new google.maps.LatLng(station['marker_latitude'], station['marker_longitude']);
var infoWindow = new google.maps.InfoWindow();
var image = 'https://marchad.fr/wp-includes/images/marchad.png';
var description = station['marker_text'];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: station['marker_ville'],
id: station['marker_id']
});
(function(marker, i) {
google.maps.event.addListener(marker, "click", function() {
var station = locations[i];
var mId = station['marker_id']; //description input field value
var contentString = ("<div id='infoWindow" + station['marker_id'] + ">" +
"<p class='texte'><strong>" + station['marker_text'] + "</strong><p>" +
"<p class='texte'>Ce staliad est géré par un " + station['marker_user_type'] + "<p>" +
"<p class='texte'><strong>Adresse : </strong>" + station['marker_adresse'] + "<p>" +
"<p class='texte'><strong>Jour de permanence : </strong>" + station['marker_day'] + "<p>" +
"<p class='texte'><strong>Dépôts : </strong>de " + station['marker_depot_start_time'] + " à " + station['marker_depot_end_time'] + "<p>" +
"<p class='texte'><strong>Retraits : </strong>de " + station['marker_start_time'] + " à " + station['marker_end_time'] + "<p>" +
"<p class='texte'><strong>Téléphone : </strong>" + station['marker_user_contact'] + "<p>" +
"<p class='texte'><strong>Mail : </strong>" + station['marker_contact_mail'] + "<p>" +
"<p class='texte'><strong>Commentaire : </strong>" + station['marker_commentaire'] + "<p>" +
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker' + station['marker_id'] + '">' +
'<input id="idInput' + station['marker_id'] + '" type="hidden" name="marker-id" class="marker-id' + station['marker_id'] + '" value=' + station['marker_id'] + ' />' + station['marker_id'] + '</input>' +
'</form>' +
'<input id="inputButton' + station['marker_id'] + '" type="button" id="save-marker' + station['marker_id'] + '" name="save-marker" class="save-marker' + station['marker_id'] + '" data-id="' + station['marker_id'] + '" value="M\'inscrire" />' +
'<div id="test' + station['marker_id'] + '">' + vendorId + '</div>' +
'<span class="info-content' + station['marker_id'] + '">' +
'<h1 class="marker-heading"></h1>' +
'</span>' +
"</div>"
);
infoWindow.close();
infoWindow.setContent(contentString);
infoWindow.open(map, this);
var class_name_removeBtn = 'remove-marker' + station['marker_id'];
var class_name_saveBtn = 'save-marker' + station['marker_id'];
google.maps.event.addListenerOnce(infoWindow,'domready', function() {
var removeBtn = document.getElementsByClassName(class_name_removeBtn);
removeBtn = removeBtn[removeBtn.length-1];
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
saveBtn = saveBtn[saveBtn.length-1];
console.log(removeBtn);
console.log(saveBtn);
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function(event) {
var class_name_mReplace = 'info-content' + station['marker_id'];
var class_name_mName = 'marker-id' + station['marker_id'];
var mReplace = document.getElementsByClassName(class_name_mReplace); //html to be replaced after success
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var mId = station['marker_id'];
var vId = vendorId;
console.log(mReplace);
console.log(mName);
console.log(mId);
console.log(vId);
if (mId !== '') {
alert("click");
save_marker(mName, mId, mReplace, vId); //call save marker function
} else {
alert("Something went wrong. Please contact admin");
}
});
if (typeof removeBtn !== 'undefined') //continue only when save button is present
{
google.maps.event.addDomListener(removeBtn, "click", function(event) {
var class_name_mName = 'marker-id' + station['marker_id'];
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var vId = vendorId;
remove_marker(mName, vId);
});
}
})
});
})(marker, i);
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map-canvas {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="submit" type="button" value="submit" />
<div id="map-canvas"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly" async></script>
</body>
</html>
Mine works like this.. detect click event within info window
google.maps.event.addListener(infowindow, 'domready', function() {
$('.classname').click(function(){
// code
});

Google Maps search for duplicate lat and lng

For each location I'm adding a png icon.
In my database I have many entries with the same lat and lng. Is there a way I can find the entries with the duplicate lat and lng and apply a different icon?
function displayStores(result){
if (result.length > 0){
for (i=0;i<result.length;i++){
//Append Store Address on Sidebar
var html = getEmbedHTML(i+1,result[i].name,result[i].address,result[i].distance);
$("#divStores").append(html);
//place a marker
var image = 'images/number_' + parseInt(i+1) + '.png';
var latlng = new google.maps.LatLng(result[i].lat,result[i].lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var msg = 'Location : ' + result[i].name + '<br/> ';
msg = msg + 'Address : ' + result[i].address + '<br/> ';
attachMessage(marker, msg);
}
} else {
$("#divStores").html('No Stores Found');
}
}
You can sort the points and compute the difference. When it's greater then 0 then you can change the icon.

Google map info box run incorrectly

I'm trying to create a group of markers with info box attached. However, no matter which marker I click, it always opens the info box of the last detailmarker. Anyone know why? Please help.
var stepDisplay = new google.maps.InfoWindow();
function AddDetailMarker(map, itinerary) {
var markers = [];
for (var i = 1; i < itinerary.Legs.length; i++) {
var position = new google.maps.LatLng(itinerary.Legs[i].BusStop.Latitude, itinerary.Legs[i].BusStop.Longitude);
var title = itinerary.Legs[i].BusStop.Code + ": " + itinerary.Legs[i].BusStop.Location + " " + itinerary.Legs[i].BusStop.Street + ", Quận " + itinerary.Legs[i].BusStop.Ward;
var detailmarker = new google.maps.Marker({
position: position,
map: map,
title: title,
icon: "/Content/img/customized_marker/" + "blue" + "/" + "bus-stop2" + ".png"
});
google.maps.event.addListener(detailmarker, 'click', function () {
stepDisplay.setContent(title);
stepDisplay.open(map, detailmarker);
});
markers[i-1] = detailmarker;
}
}
Edit: possible dublicate of Google maps infowindow showing on wrong marker. I've tried all the solutions I found here and none works.
Yes, this is exactly the same problem as the other one you linked to, and the solution for your code is the same - put the code to create each marker into a function, and call that function in your loop:
var stepDisplay = new google.maps.InfoWindow();
function AddDetailMarker(map, itinerary) {
for (var i = 1; i < itinerary.Legs.length; i++) {
addLegMarker( map, itinerary.Legs[i] );
}
}
function addLegMarker( map, leg ) {
var position = new google.maps.LatLng(leg.BusStop.Latitude, leg.BusStop.Longitude);
var title = leg.BusStop.Code + ": " + leg.BusStop.Location + " " + leg.BusStop.Street + ", Quận " + leg.BusStop.Ward;
var detailmarker = new google.maps.Marker({
position: position,
map: map,
title: title,
icon: "/Content/img/customized_marker/" + "blue" + "/" + "bus-stop2" + ".png"
});
google.maps.event.addListener(detailmarker, 'click', function () {
stepDisplay.setContent(title);
stepDisplay.open(map, detailmarker);
});
}
Do you see why that fixes it? The title and detailmarker are now specific to each invocation of addLegMarker(). In the original code, there was only a single copy of each of these variables, shared among all markers.

Javascript shows only last markers

The following code grabs some JSON data from /home.json URL which contain 5 microposts by 6 users. However, only the last 4 markers are shown (not even the 5th !!). I have spend 2 days to find the bug but unfortunately I can't really get why this dosen't work. If anyone could help me I would really appreciate it!
I have tested all lon/Lat variables through alert! All of them have the appropriate data. The map should be ok since the last 4 are shown !! Most probably the problem lies with my closure definition but I really cannot understand what I am doing wrong..
var GMAPS = window.GMAPS || {};
GMAPS.mainMap = function() {
var map;
var infowindow = new google.maps.InfoWindow();
var jsonObject = {};
function addMarkers() {
var xhr = new XMLHttpRequest();
xhr.open( "GET", "/home.json", true );
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 && xhr.status == 200 ) {
jsonObject = JSON.parse( xhr.responseText );
for (var i=0; i<jsonObject.length; i++) {
for (var j=0; j<jsonObject[i].microposts.length; j++) {
(function(Name, Title, Content, Latitude, Longitude) {
return function() {
//alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n"); //<-- this works!
var position = new google.maps.LatLng(Latitude, Longitude);
var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
+ "<br />" + Content;
var marker = new google.maps.Marker({
position: position,
title: Title,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, contentString));
};
})(jsonObject[i].name, jsonObject[i].microposts[j].title,
jsonObject[i].microposts[j].content,
jsonObject[i].microposts[j].lat,
jsonObject[i].microposts[j].lon)();
}
}
}
};
xhr.send(null);
}
function createMap() {
map = new google.maps.Map(document.getElementById('main_map'), {
zoom: 10,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
scrollwheel: false,
center: new google.maps.LatLng(37.975327,23.728701),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function initAddress() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
var position = new google.maps.LatLng(0, 0);
map.setCenter(position);
}
}
function showPosition(position) {
var position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(position);
}
return {
initMap : function() {
createMap();
initAddress();
addMarkers();
}
};
}();
document.addEventListener("DOMContentLoaded", GMAPS.mainMap.initMap, false);
** Note: you have an unnecessary extra set of parens at the end of your IIFE.
Before your IIFE (inside the innermost for-loop), try adding:
var jObj = jsonObject[i], mPost = jObj.microposts[j];
Then in replace the arguments to the IIFE with:
(function(Name, Title, Content, Latitude, Longitude) {
return function() {
//alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n"); //<-- this works!
var position = new google.maps.LatLng(Latitude, Longitude);
var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
+ "<br />" + Content;
var marker = new google.maps.Marker({
position: position,
title: Title,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, contentString));
};
})(jObj.name, mPost.title, mPost.content, mPost.lat, mPost.lon);
The following code should work. I still don't understand why you have the extra set of parentheses.
xhr.onreadystatechange = function() {
var i = 0, j = 0;
if ( xhr.readyState == 4 && xhr.status == 200 ) {
jsonObject = JSON.parse( xhr.responseText );
for (var ilen = jsonObject.length; i < ilen;) {
for (var jObj = jsonObject[i++], jlen = jObj.microposts.length; j < jlen;) {
var mPost = jObj.microposts[j++];
(function(Name, Title, Content, Latitude, Longitude) {
return function() {
//alert(Name + "\n" + Title + "\n" + Content + "\n" + Latitude + "\n" + Longitude + "\n"); //<-- this works!
var position = new google.maps.LatLng(Latitude, Longitude);
var contentString = "<h4>" + Name.bold() + "</h4>" + "<br />" + Title.bold()
+ "<br />" + Content;
var marker = new google.maps.Marker({
position: position,
title: Title,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, contentString) {
return function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
}
})(marker, contentString));
};
})(
jObj.name, mPost.title, mPost.content, mPost.lat, mPost.lon
);
}
}
}
};

Fusion Tables map broken after search

here's a Fusion Tables map that's broken after a search. It does everything well before I do a search. The points on the map just don't show (although the information in the table below it gets updated).
What am I doing wrong?
//write the map on page load
$(document).ready(function() {
createMap();
});
//ft layer
var layer;
//ft table
var tableid = 4176964;
//map
var map;
//geocoder instance
var geocoder = new google.maps.Geocoder();
//infowindow
var infowindow;
//gviz
var table;
//FT data in gviz object
var datatable;
//center of map
var center = new google.maps.LatLng(52.146973340644735, 4.7021484375);
//default zoom
var zoom = 7;
google.load('visualization', '1', {
'packages': ['table']
});
function createMap() {
//map options
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: center,
zoom: zoom,
minZoom: 2,
maxZoom: 12,
scrollwheel: true,
disableDragging: true,
mapTypeControl: false,
navigationControl: true,
streetViewControl: false,
scaleControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
}
});
//intial fusion layer & supress fusion info window
layer = new google.maps.FusionTablesLayer(tableid, {
suppressInfoWindows: true,
query: "SELECT Latitude FROM " + tableid,
map: map
});
//adds click listener on layer
google.maps.event.addListener(layer, 'click', function(e) {
if (infowindow) infowindow.close();
else infowindow = new google.maps.InfoWindow();
//write FT data to info window
text = infowindow.setContent('<p>Op <b>' + e.row['Datum'].value + '</b> storte een ' + e.row['Type'].value + ' van ' + e.row['Vliegmaatschappij'].value +' met registratienummer ' + e.row['Registratie'].value + ' neer bij <b>' + e.row['Locatie'].value + '</b>.<p><p>Hierbij overleden ' + e.row['Slachtoffers'].value + ' van de ' + e.row['Inzittenden'].value + ' inzittenden en ' + e.row['Grond'].value + ' overleden op de grond.<p><p>Meer informatie op Aviation Safety Network.');
infowindow.setPosition(e.latLng);
map.setCenter(e.latLng);
infowindow.open(map);
});
//query FT data for visualization
var queryText = encodeURIComponent("SELECT Datum, Locatie, Type, Registratie, Vliegmaatschappij, Slachtoffers, Inzittenden, Grond FROM 4176964 ORDER BY 'Datum' ASC");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
}
//write FT data to table
var getData = function(response) {
console.log('getData');
console.log(response);
table = new google.visualization.Table(document.getElementById('visualization'));
datatable = response.getDataTable();
table.draw(datatable, {
showRowNumber: true
});
//add table listener when row clicked
google.visualization.events.addListener(table, 'select', selectHandler);
}
//match table data to map data
function selectHandler() {
//get lat/lng from FT
var selection = table.getSelection();
var Datum = datatable.getValue(selection[0].row, 0);
var Locatie = datatable.getValue(selection[0].row, 1);
var Type = datatable.getValue(selection[0].row, 2);
var Registratie = datatable.getValue(selection[0].row, 3);
var Vliegmaatschappij = datatable.getValue(selection[0].row, 4);
var Slachtoffers = datatable.getValue(selection[0].row, 5);
var Inzittenden = datatable.getValue(selection[0].row, 6);
var Grond = datatable.getValue(selection[0].row, 7);
infoWindowContent = ('<p>Op <b>' + e.row['Datum'].value + '</b> storte een ' + e.row['Type'].value + ' van ' + e.row['Vliegmaatschappij'].value +' met registratienummer ' + e.row['Registratie'].value + ' neer bij <b>' + e.row['Locatie'].value + '</b>.<p><p>Hierbij overleden ' + e.row['Slachtoffers'].value + ' van de ' + e.row['Inzittenden'].value + ' inzittenden en ' + e.row['Grond'].value + ' overleden op de grond.<p><p>Meer informatie op Aviation Safety Network.');
}
function changeSearch(dater) {
dater = document.getElementById('newDatum').value;
console.log('dater: ' + dater);
//with a query based on the variables
var sql = "SELECT Datum, Locatie, Type, Registratie, Vliegmaatschappij, Slachtoffers, Inzittenden, Grond FROM " + tableid + " WHERE Datum CONTAINS '" + dater + "' ORDER BY 'Datum' ASC";
var polySql = "SELECT Latitude FROM " + tableid + " WHERE Datum CONTAINS '" + dater + "'";
console.log('SQL: ' + sql);
console.log('Polygon-SQL: ' + polySql);
layer.setOptions({
query: polySql,
map: map
});
var queryText = encodeURIComponent(sql);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
//adds a click listener on search layer
google.maps.event.addListener(layer, 'click', function(e) {
if (infowindow) infowindow.close();
else infowindow = new google.maps.InfoWindow();
//writes the info window on search layer
infowindow.setContent('<p>Op <b>' + e.row['Datum'].value + '</b> storte een ' + e.row['Type'].value + ' van ' + e.row['Vliegmaatschappij'].value +' met registratienummer ' + e.row['Registratie'].value + ' neer bij <b>' + e.row['Locatie'].value + '</b>.<p><p>Hierbij overleden ' + e.row['Slachtoffers'].value + ' van de ' + e.row['Inzittenden'].value + ' inzittenden en ' + e.row['Grond'].value + ' overleden op de grond.<p><p>Meer informatie op Aviation Safety Network.');
infowindow.setPosition(e.latLng);
map.setCenter(e.latLng);
infowindow.open(map);
});
}
//end function
This works for a query on the map:
SELECT Latitude FROM 4176964 WHERE Datum <= '16 JAN 1950'
I suspect you need to treat the data as a number (even though you specify it as a string)

Categories