Guys need a bit of help with google maps, I'm creating a tracking web app using MySQL DB coordinates, the tracking works well so far except the google map markers keep repeating when refreshed, I have set the map marker refresh using a setInterval function for every 5 seconds(for testing). I've tried clearoverlays() methods and remove map markers method(from google sample) but doesn't work. Appreciate your help, thank you
<script defer
src="https://maps.googleapis.com/maps/api/js?key="KEY"8&callback=initMap">
</script>
<script type="text/javascript">
setInterval(function () {
BindMarker();
}, 5000);
var customIcons = {
blue: { icon: 'blue48.png'},
};
var marker;
var map = null;
var infoWindow = null;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(1.4370993, 110.3387572),
zoom:15,
});
infoWindow = new google.maps.InfoWindow;
}
function BindMarker() {
downloadUrl('maps1.php', function (data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var icon = customIcons["blue"] || {};
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.BOUNCE,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
}
});
}
function bindInfoWindow(marker, map, infoWindow) {
google.maps.event.addListener(marker, 'click', function () {
map.setCenter(marker.getPosition());
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
request.önreadystatechange = doNothing;
callback(request, request.status); }
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() { }
</script>
The functions I tried are given below( I called the remove overlays function, remove markers and also the delete markers function before BindMarker() inside the setInterval function so that it would remove the markers before binding new markers
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) { markers[i].setMap(map); }
}
function clearMarkers() {setMapOnAll(null); }
function deleteMarkers() {clearMarkers(); markers = [];}
function clearOverlays() {
while(markers.length) { markers.pop().setMap(null); }
markers.length = 0;
}
I believe you've confounded the examples, which your attempted code shows verbatim and what your code is actually doing.
It the sample code you're drawing from, the variable markers is an array of Google Map marker objects. So this code makes sense in that regard:
function deleteMarkers() {clearMarkers(); markers = [];}
But, your code is not creating an array of those objects. Your code does not have a variable named markers that is accessible outside of the downloadUrl() function. The variable markers does show up inside that function, but it contains an HTMLCollection element - not an array of markers.
To fix this you need to create an array named markers right after the variable name marker is created.
Then, within the for loop, just after you create the marker push that marker on to the markers array. You will also have to rename the existing markers variable to something more appropriate like markerElements.
Now, the deleteMarkers() function will work as expected.
Related
I would like to remove a marker in Google Maps, but I don´t understand this. Please help me.
My Validation.js:
function initialize() {
//geocodierungs Funktion damit Geocoding funktioniert
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom:5,
center: new google.maps.LatLng(48.136607,11.577085),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var pos=new google.maps.LatLng(48.2,11);
var marker = new google.maps.Marker({
position:pos,
map:map,
title: 'test'
});} setInterval(function(){
//$.post('nav_schnittstelle.php',{}).done(aktualisiereKartendaten);
alert('test');
pos.setMap(null); },10000);
How can I use setMap(Null);? I don´t understand this.
Try making a button and a listener to test your code.
To remove a marker from the map, call the setMap() method passing null as the argument.
marker.setMap(null);
Note that the above method does not delete the marker. It simply removes the marker from the map. If instead you wish to delete the marker, you should remove it from the map, and then set the marker itself to null.
Following the sample code in the document:
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
To remove a single marker, see the related SO question code snippet:
marker.addListener("dblclick", function() {
marker.setMap(null);
});
Hope this helps!
I have 2 different events, please correct me if i am doing this wrong,
//initializing the map
google.maps.event.addDomListener(window, 'load', initialize);
//initializing the markers
google.maps.event.addListener(map, 'idle', showMarkers);
The first event is to initialize the map (set it up), the second event is for querying the database for new markers when the current map bounds change (not functional yet)
Since I have defined "map" inside the initialize function, how can I access it outside the function and pass it to the second event? As you can see i have declared it before the functions as a global variable but it is still undefined as the event argument, i have been stuck on this for days
var map;
function initialize(){
//defining map options
var mapLatlng = new google.maps.LatLng(37.09024, -100.712891);
var mapOptions = {
zoom: 4,
center: mapLatlng
}
//defining the map itself
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function showMarkers(){
Parse.initialize("X","X");
var query = new Parse.Query("business_and_reviews");
var results = new Parse.Object("business_and_reviews");
query.equalTo("name","McDonalds");
query.find({
success: function(results) {
console.log(results);
for (var i = 0; i < results.length; i++) {
var object = results[i];
}
var lat = (object["attributes"]["lat"]);
var lng = (object["attributes"]["lng"]);
console.log(lat);
console.log(lng);
//adding the marker from the query
var marker = new google.maps.Marker({
position: mapLatlong,
map: map,
title: 'Hello World!'
});
},
error: function(object, error) {
}
});
}
//initializing the map
google.maps.event.addDomListener(window, 'load', initialize);
//initializing the markers
google.maps.event.addListener(map, 'idle', showMarkers);
For the second event "map" is undefined
SOlved it! put the idle event listener inside the initialize function and it works like a charm! I guess initilize isn't to initialize the page initially but runs constantly
I'm coding a demo of how I want a future search function to work. I want to query google on an address or area and return the area bounds as well as nearby places. To do this, I am using places autocomplete, geocode, and places search.
So far I am successfully getting predicted search queries resulting in the bounds being drawn as a rectangle on my map. However, when I try to implement markers for the place search result no markers are appearing on my map. I know the search is working because putting an alert in the createMarker function on each location returns several lat/lng's that coincide with my area.
I suspect that maybe the map object is not being passed to my createMarker function, but I am kind of a noob when it comes to Javascript. I tried passing an additional parameter but it didn't do much.
It should be noted that I am able to create a marker within the initialize function, when I attempt to just create one static marker.
EDIT: I have removed the type parameter for the place search request, but the code doesn't work even with the parameter ['store'].
var map;
var infowindow;
function initialize() {
var view_lat = document.getElementById('view_lat').value;
var view_lng = document.getElementById('view_lng').value;
var focus = new google.maps.LatLng(view_lat,view_lng);
var swlat = document.getElementById('swlat').value;
var swlng = document.getElementById('swlng').value;
var nelat = document.getElementById('nelat').value;
var nelng = document.getElementById('nelng').value;
var map_canvas = document.getElementById('map-canvas_embed');
var map_options = {
center: new google.maps.LatLng(parseFloat(view_lat), view_lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var mysw = new google.maps.LatLng(swlat,swlng)
var map = new google.maps.Map(map_canvas, map_options)
var rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(swlat, swlng),
new google.maps.LatLng(nelat, nelng))
});
var request = {
location: focus,
radius: 500
};
var place_search = new google.maps.places.PlacesService(map);
place_search.nearbySearch(request,callback)
}
Handles the result from google places search
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.setMap(map);
}
Autocomplete variables
var input = document.getElementById('location');
var options = {
componentRestrictions: {country: 'se'},
types: ['geocode']
}
var searchform = document.getElementById('searchform');
var place;
var autocomplete = new google.maps.places.Autocomplete(input, options);
Add listener to detect autocomplete selection
google.maps.event.addListener(autocomplete, 'place_changed', function () {
place = autocomplete.getPlace();
//console.log(place);
});
Add listener to search (This function isn't working, hence my work around in the initialize function)
searchform.addEventListener("submit", function() {
var newlatlong = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
map.setCenter(newlatlong);
marker.setPosition(newlatlong);
map.setZoom(12);
google.maps.event.trigger(map, 'resize');
});
Reset the inpout box on click
input.addEventListener('click', function(){
input.value = "";
});
Call the initialize function
google.maps.event.addDomListener(window, 'load', initialize);
Indeed it looks like a problem of JavaScript's scope.
Consider these lines of your code:
function initialize() {
//...
var map = new google.maps.Map(map_canvas, map_options)
//...
}
Declaring map inside the initialize function makes your map variable unreachable out of your initialize function.
So when you try to reach it in your searchform, map.setCenter() will show in your console that map is undefined.
You could solve your issue in several ways.
declare map at the beginning of your script (before initialize is executed, anyways)
declare the searchform.addEventListener("submit", function(){}) inside your initialize() function and use it before initialize() ends its execution.
I have the following code, and having read this, i understand it wont work because the getJSON call is asynchronous. How do i need to change this so that the MarkerClusterer function gets triggered with a full set of markers? I've tried putting the MarkerClusterer function inside the getJSON call but with no luck...
var mcOptions = {gridSize: 50, maxZoom: 9};
var markers = [];
function parse_json(json) {
if (json.length > 0) {
for (i=0; i<json.length; i++) {
var report = json[i];
var latLng = new google.maps.LatLng(report.latitude, report.longitude);
markers[i] = new google.maps.Marker({
position: latLng,
title: report.name + ' ' + report.surf_size_ft_round,
url: "/place/"+report.slug
});
google.maps.event.addListener(markers[i], 'click', function() {
window.location.href = markers[i].url;
});
markers.push(markers[i]);
}
}
};
$.getJSON('<%= request.fullpath + ".json" %>', function(stream) {
if (stream.length > 0) {
parse_json(stream);
alert(markers[1].title); //sanity check - gives result
}
});
alert(markers[5].title); // sanity check - empty
var mc = new MarkerClusterer(map, markers, mcOptions);
Why not put this code snippet:
mc = new MarkerClusterer(map, markers, mcOptions);
inside the anonymous callback function in your $.getJSON? Just declare var mc; somewhere outside the $.getJSON scope to be able to have access to it elsewhere.
Alternatively, you can fire an event at the end of your parse_json function, listen to that event and then fire up another function that creates your MarkerClusterer object when the event has fired. Check this out: How to trigger event in JavaScript?
EDIT:
Upon inspecting your code a bit more, I can see that you set markers[i] to a new Marker instance and then push onto the markers array that same instance. You probably want to either set markers[i] to a new Marker instance or you want to create a var marker, setting it to a new Marker instance and then pushing on the markers array.
Maybe you need to put it inside the success function you give as an input to $.getJSON?
$.getJSON('<%= request.fullpath + ".json" %>', function(stream) {
if (stream.length > 0) {
parse_json(stream);
alert(markers[1].title); //sanity check - gives result
mc = new MarkerClusterer(map, markers, mcOptions);
}
});
alert(markers[5].title); // sanity check - empty
I have functions that when a li element is clicked markers are added to the map. If another li is clicked then the original markers are removed and the new one appearr.
The issue I am having is that the markers are placed on the map when a li is clicked for the first time. When a second li is clicked the markers are removed but the new ones are not added. I get no error in firebug. I cant see what I am missing.
$(document).ready(function() {
$(".markerSelection").click(function() {
var selectionId = $(this).attr("id");
drop(selectionId);
});
});
var markers = {
shopping : [
new google.maps.LatLng(52.26183, -7.11339),
new google.maps.LatLng(52.26134, -7.11226),
new google.maps.LatLng(52.26067, -7.11181),
new google.maps.LatLng(52.26003, -7.11033)],
cars : [
new google.maps.LatLng(52.26183, -7.11339),
new google.maps.LatLng(52.26134, -7.11226),
new google.maps.LatLng(52.26067, -7.11181),
new google.maps.LatLng(52.26003, -7.11033)]
};
var iterator = 0;
function drop(selectionId) {
clearOverlays();
for (var i = 0; i < markers[selectionId].length; i++) {
setTimeout(function() {
addMarker(selectionId);
}, i * 200);
}
}
function addMarker(selectionId) {
marker = new google.maps.Marker({
position: markers[selectionId][iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
});
iterator++;
markersArray.push(marker);
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
I reviewed your code one more time, and I think the problem is with iterator, which is initialized to 0 in global scope. That is why the first time it works okay, but after that, indices exceed. It seems you should set it to zero at the beginning of the drop() function.
However it makes more sense if you pass index as a second parameter of addMarker() instead of an outer variable which is handled in drop() and complicate you code.
You have defined markers as a Json variable, but I don't know what you mean by markers[selectionId]! Markers is not defined as an array and it seems it's not correct to refer to it by index!