Issue with Cache, Maps and MarkerClusterer - google-maps

I have a website built from Google Maps and using MarkerClusterer. This site works fine most of the time, but there will be times when multiple users will be online and a filtered marker sets request will be returned incorrectly.
Example: I filter to a set of markers based on a set of filter parameters. As this is processing someone else also filters to a different set of markers and those markers are returned to me instead of my request.
I can also see this issue occur if I sit on the page and just hit refresh. I have tested in our test environment with 2 users. By having one user filter to a set of markers and when the second user refreshes their browser window they see the same set of filtered markers. The markers of the first user.
I have seen example fixes were it is discussed to use a CacheBuster by adding the Date to the URL, but in using the MarkerCluserer code I do not see where to add that as an option. It has also been asked not to do this.
Data is coming from the server in an array object. markerclusterer.js is located locally in the Visual Studio Project. Here is the Script on the page that generates the map:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.11&sensor=false"></script>
<script type="text/javascript" src="/Scripts/markerclusterer.js"></script>
<script type="text/javascript">
var infowindow;
var map;
var markerdataLength; //en - 5-8-2013
var prev;
$(document).ready(function () {
setTimeout("gmarkers()", 500);
});
function gmarkers() {
markerdataLength = 0;
$("#map_canvas").fadeTo(500, 0.3);
$("#pwait").show();
$.ajax({
type: "POST",
url: "MapSearch.aspx/GetMarkers",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#map_canvas").fadeTo(0, 0.3);
$("#pwait").show();
var markerdata;
markerdata = msg.d;
msg = null;
var latlng = new google.maps.LatLng(52.50, -98.35);
var myOptions = {
zoom: 3,
center: latlng,
//mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_CENTER
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
}
};
//initialize the info window (balloon popup)
infowindow = new google.maps.InfoWindow();
//draw the map with the above settings
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
/***************************MARKER CLUSTERER **********************************************/
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x24&chco=' +
'FFFFFF,008CFF,000000&ext=.png'; //Blue
var markers = [];
if (markerdata != "undefined" & markerdata.length > 0) { //run this code if the data is not null. data is the markers in json format
markerdataLength = markerdata.length; //en - 5-8-2013
var i = 0;
var ro = new RepeatingOperation(function () {
var dataWell = markerdata[i];
var mlatLng = new google.maps.LatLng(dataWell.la, dataWell.lo);
var marker = new google.maps.Marker({
id: dataWell.id,
position: mlatLng,
title: dataWell.t,
icon: imageUrl //iconstring
});
//set the marker click code to show the info window
var fn = markerClick(dataWell.id);
google.maps.event.addListener(marker, 'click', fn);
google.maps.event.addListener(marker, 'clusteringend', clusteringDone()); //en - 5-8-2013
markers.push(marker);
if (++i < markerdata.length) { ro.step(); }
else {
var mcOptions = {
gridSize: 90, //default grid size is 60 was using 35. higher #'s draw faster.
maxZoom: 20, //defines how close u are before no more clusters are drawn
minimumClusterSize: 15
};
var mc = new MarkerClusterer(map, markers, mcOptions);
}
}, 100);
ro.step();
}
else {
alert("No wells were found.");
$("#map_canvas").fadeTo(300, 1);
$("#pwait").hide();
}
}
});
}

Related

Dynamic marker and infoWindow Google Maps API using Google App Engine parsing through a JSON file

Hi I'm new to stackoverflow (and coding) but I am working on a web-application where I want to add dynamic markers and infowindows based on an extracted JSON file. There are over 200 markers, so they need to be dynamic. I have code that works to add markers but as soon as I add infoWindows it doesn't. Can anybody see why? The output dropped to just one marker and no infoWindow.
Here is my code:
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
infowindow = new google.maps.InfoWindow();
for (element in data) {
new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
infowindow.setContent(data[element].country);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
}
});
}
I saw a post on stackoverflow with a similar question and tried it that way as well but didnt get any markers.
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
var json = data = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].lat, json[i].lon);
contentString = json[i].Country;
addMarkers(point, contentString);
}
}
});
function addMarkers(point, contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.push(marker);
infos.push(infowindow);
for (var j = 0; j < markers.length; j++) {
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map, markers[j]);
})
}
}
}
The output of my JSON file looks like this:
{
"AA": {
"celsius": 32.27777777777778,
"country": "AA",
"day": "25",
"lat": 12.5,
"lon": -70.017,
"month": "03"
},
...
}
There are a few issues in your code. You should read Using Closures in Event Listeners.
You should set the infowindow content on marker click (not within the loop, as you did)
You should declare the marker variable which is missing
Any variable you are using must be declared, for example for (element in data) should be for (var element in data)
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
console.log(data);
infowindow = new google.maps.InfoWindow();
for (var element in data) {
var marker = new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
google.maps.event.addListener(marker, 'click', (function(marker, element) {
return function() {
var content = 'Country: ' + data[element].country;
content += '<br>Temperature (°C): ' + data[element].celsius;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, element));
}
}
});
}
initMap();
#map {
height: 180px;
}
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

Update Marker in Google Maps without loading whole map

I have an Application in CI where i am getting the current location of a employee after every two seconds from database and draw its current location marker
my code is working but after every 2 seconds it will update the marker by showing a new location marker but keep showing old markers too.
i want to delete old marker of employee before showing the new marker.
here is my code
<script>
function initMap4(data,id) {
var map2 = new google.maps.Map(document.getElementById('map2'), {
zoom: 8,
center: new google.maps.LatLng(31.1704,72.7097),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({});
window.setInterval(function(){
$.ajax({
type: 'POST',
url: '<?php echo base_url() ?>salesman/get_salesman_by_id',
data : { id: id},
success: function (response) {
var result = response ;
update(result);
}
});
},2000);
function update(data){
var clicked = false;
var locations2;
if(data){
locations2= JSON.parse(data);
}else{
locations2 = JSON.parse('<?php echo $clocation; ?>');
}
var locations_array2= [];
$.each(locations2[0], function( index, value ) {
locations_array2.push([
value.first_name,
value.lat,
value.long,
value.checkin_time,
value.checkout_time,
]);
});
locations2=locations_array2;
for (i = 0; i < locations2.length; i++)
{
var currTime = Date.now() - 300000;
var online = locations2[i][5];
var MyOnlineMarker = {
position: new google.maps.LatLng(locations2[i][1], locations2[i][2]),
map: map2,
};
if(locations2[i][4] == "" ){
marker = new google.maps.Marker(MyOnlineMarker);
}else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations2[i][1], locations2[i][2]),
map: map2,
icon: 'assets/Images/red.png'
});
}
}
}
}
</script>
Ive solved it
by pushing marker in an array than delete them

Google map integration issue : "This site has exceeded its daily quota for maps

I am getting the longitude and latitude from AJAX and giving me more 120 on every page load. Marking the result locations into google map and using browser key. It was working fine, but suddenly it stopped working and getting 'This site has exceeded its daily quota for maps. If you are the creator of this site, please visit the documentation to learn more' error plus page hangs. It has been more than 24 hours, but the problem remains same. I tried to found out the solution but no luck and I changed new API key.
JS files:
<script src="http://open.mapquestapi.com/sdk/js/v7.2.s/mqa.toolkit.js?key=my-browser-key"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry"></script>
JS code:
var map;
var infowindow;
var service;
var address = "United Kingdom";
var latitude = '51.497801';
var longitude = '-0.065918';
var myLatlng = new google.maps.LatLng(latitude,longitude);
var geocoder = new google.maps.Geocoder();
var markers = '';
function initialize() {
var bounds = new google.maps.LatLngBounds();
var getTeamsUrl = Routing.generate('getAllUsers',{});
$.ajax({
url : getTeamsUrl,
type : 'POST',
data : 'type=getAllUsers',
datatype : 'json',
async : false,
success : function(data){
markers = JSON.parse(data);
}
});
console.log(markers.length);
myLatlng = new google.maps.LatLng(latitude,longitude); /* latitude and longitude*/
var mapOptions = {
zoom: 7,
center: myLatlng,
panControl:true,
draggable: true,
zoomControl:true,
scrollwheel: false,
scaleControl:false,
rotateControl:true,
mapTypeControl:true,
streetViewControl:true,
overviewMapControl:true,
navigationControl: true,
mapTypeId:google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
for( i = 0; i < markers.length; i++ ){
name = markers[i]['title']+' '+ markers[i]['first_name']+' '+ markers[i]['surname'];
address = markers[i]['address_1']+' '+ markers[i]['address_2']+', '+ markers[i]['city']+', '+ markers[i]['postcode'];
longitude = markers[i]['longitude'];
latitude = markers[i]['latitude'];
addMarkerOnMapUsingLatLng(latitude, longitude, name, address, '', 1);
}
}
function addMarkerOnMapUsingLatLng(lat,lng, name, address, icon, selected){
if(lat!='' && lng!=''){
myLatlng = new google.maps.LatLng(lat,lng);
}
var mapOptions = {
zoom: 7,
center: myLatlng,
panControl:true,
draggable: true,
zoomControl:true,
scrollwheel: false,
scaleControl:false,
rotateControl:true,
mapTypeControl:true,
streetViewControl:true,
overviewMapControl:true,
navigationControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
},
streetViewControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM
},
mapTypeId:google.maps.MapTypeId.ROADMAP
}
if(selected==1){
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
map.setCenter(myLatlng);
}
var infowindow = new google.maps.InfoWindow({
content: address,
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: name/*,
icon : icon*/
});
google.maps.event.addListener(marker, 'click', function(){
/* infoWindow.setContent(address); */
infowindow.open(map, marker);
});
}
Since you are using Google Maps JavaScript API, the users of this standard API is FREE until exceeding 25,000 map loads per 24 hours.
Just take note that for customers with active implementations of the Google Maps JavaScript API prior to June 22, 2016, quota exceptions may apply. In certain instances, map loads in excess of 25,000 per day may be allowed free of charge until October 12, 2016.
And if you exceed the free usage limits,the billing is $0.50 USD / 1000 additional requests, up to 100,000 per 24 hours.
Just check the link above to know more about Google Maps API Usage Limits

Google maps centered load failure

Well I'm having this problem, load the map once and everything works perfect. The second time or once update the map does not load ok, but not centered load when navigating on you can see the marks that are made but is deformed or simply lost.
I have tried several ways to solve this problem, first and most common I found was to use google.maps.event.trigger(map 'resize') but it did not work then and logic, try that whenever loading map is executed, create a new map, with the same data and focused but neither worked for me. It may be also the way I use the map. I am using the plugin of the camera in my application, the user takes a photo and this should detect where I draw the picture and display the map. Each time the view is opened, the plug of the camera, in the process of taking and show the picture is where I call the appropriate functions to load the map and this has me a bit tricky immediately loaded I have a good time locked in this problem, I found solutions serve me but only for the browser, the device does not work. I am using ionic framework and plugins cordova.
Controller :
.controller("CamaraCtrl", function($scope,$rootScope, Camera,$cordovaGeolocation,$state,$location,$ionicSideMenuDelegate) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var latitud_actual = position.coords.latitude
var longitud_actual = position.coords.longitude
$scope.latitud = latitud_actual;
$scope.longitud = longitud_actual;
//$scope.map = new google.maps.Map(document.getElementById("mapa_ubicacion"), mapOptions);
}, function(err) {
// error
});
function initialize() {
var mapOptions = {
center: new google.maps.LatLng($scope.latitud, $scope.longitud),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.setMarker(map, new google.maps.LatLng($scope.latitud, $scope.longitud), 'Yo', '');
$scope.map = map;
}
$scope.setMarker = function(map, position, title, content) {
var marker;
var markerOptions = {
position: position,
map: map,
title: title
};
marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'click', function () {
// close window if not undefined
if (infoWindow !== void 0) {
infoWindow.close();
}
// create new window
var infoWindowOptions = {
content: content
};
infoWindow = new google.maps.InfoWindow(infoWindowOptions);
infoWindow.open(map, marker);
});
}
$scope.mostrar_form = false;
$scope.mostrar_boton_view = false;
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.lastPhoto = imageURI;
$scope.mostrar_form = true;
$scope.mostrar_boton_view = false;
google.maps.event.addDomListener(window, 'load', initialize);
initialize();
}, function() {
$scope.mostrar_boton_view = true;
}, {
quality: 75,
targetWidth: 320,
targetHeight: 320,
saveToPhotoAlbum: false
});
};
$scope.getPhoto();
})
The only solution I found was to create a function that executes the map again. It should not be as optimal but at least it solved my problem.
$scope.centrar = function(){
var mapOptions = {
center: new google.maps.LatLng($scope.latitud, $scope.longitud),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.setMarker(map, new google.maps.LatLng($scope.latitud, $scope.longitud), 'Yo', '');
$scope.map = map;
}

Google maps marker, with added directions code not showing

I seem to be having trouble adding a marker to one of my maps that I have created and I just can't seem to figure out where I am going wrong with it.
The map has been added to the site fine, and I even have the directions code working which happens to be displaying markers.
What I would like would be an initial marker to display where, in this case, the school is and have an info box on click to show the address but I just can't seem to get it displaying no matter what I try.
My code for everything is as follows:-
<div id="map_canvas" style="width:100%; height:392px;float:left;"></div>
<div id="directionsPanel" style="float:left;max-width:395px; overflow:scroll;overflow-x: hidden;"></div>
<script>
//define one global Object
var myMap = {}
//init
function initialize(){
//set up map options
var mapOptions = {
center: new google.maps.LatLng(53.964304,-2.028522),
zoom: 15,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
myMap.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myMap.directionsService = new google.maps.DirectionsService();
myMap.directionsDisplay = new google.maps.DirectionsRenderer();
myMap.directionsDisplay.setMap(myMap.map);
myMap.directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}//end init
function createMarker(point, title, content, map) {
var marker = new google.maps.Marker({
position: point,
map: map,
title: title
});
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
if(curr_infw) { curr_infw.close();} // We check to see if there is an info window stored in curr_infw, if there is, we use .close() to hide the window
curr_infw = infowindow; // Now we put our new info window in to the curr_infw variable
infowindow.open(map, marker); // Now we open the window
});
return marker;
}
//directions
var calcRoute = function() {
var start = document.getElementById("start").value,
end = document.getElementById("end").value,
request = {
origin:start,
destination:end,
durationInTraffic :true,
transitOptions: {
departureTime: new Date()
},
provideRouteAlternatives : true,
travelMode: document.getElementById("travelmode").value
};
myMap.directionsService.route(request, function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
myMap.directionsDisplay.setDirections(result);
}else{
alert("something went wrong!");
}
});
}
//script loader
var loadScript = function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyDZsY0Xbo137bDtb8wmefTogdGl82QM85s&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
Any help on this guys would be greatly appreciated before I end up becoming bald from pulling out all my hair lol.
Jason