Remove markers from map before adding new markers - javascript

I have a map where initially the markers load coming from the database, Then i have a time based Ajax request which gets the records again after every 1 minute.
Following is the code where i am using setMapOnAll(null) as from the Google maps Documentation, But its not working.
success: function(data){
var positions = [];
$.each(data.riders, function(index, value) {
positions.push({
lat: value.rider_location.lat,
lng: value.rider_location.lng,
content: value.name,
id : value.id
});
});
map.setCenter({
lat: parseInt(positions[0].lat),
lng: parseInt(positions[0].lng)
});
var infowindow = new google.maps.InfoWindow();
var marker,
i;
setMapOnAll(null); //Remove the existing markers
while(positions.length){
positions.pop().setMap(null);
}
for (i = 0; i < positions.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat,positions[i].lng),
map: map,
id : positions[i].id,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
}
}) (marker, i));
}
}
How can i remove the existing markers before adding new ones.

there is method marker.setMap(null) as google docs https://developers.google.com/maps/documentation/javascript/markers
you need create array of markers then remove all from map in loop by call method marker.setMap(null)
var markers = [];
for (i = 0; i < positions.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat,positions[i].lng),
map: map,
id : positions[i].id,
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
}
}) (marker, i));
}

You should add this function to your code and call it where you add new markers then add new markers. This will delete the previous markers.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}

Related

Toggle Show/Hide Google Marker with 1 button

I am trying to toggle a button which will hide/show the google marker placed in the map. I have been searching for an answer on SOF but all offered array method. I am wondering if it is possible to do it without array.
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 1.3420894594991328, lng: 103.83490918886719},
});
var ntuc = {
lat: 1.32805676,
lng: 103.9216584
};
var ntucmap = new google.maps.Marker({
position: ntuc,
map: map,
icon: 'https://maps.google.com/mapfiles/kml/paddle/blu-stars.png'
});
}
function toggleNTUCmap() {
if (!ntucmap.getVisible()) {
ntucmap.setVisible(true);
} else {
ntucmap.setVisible(false);
}
}
Button
<button class="button-oj pure-button" onclick="toggleNTUCmap()">
<i class="fas fa-hospital"></i> NTUC</button>
For function toggleNTUCmap(), I have tried the following which still won't work.
ntucmap.setMap(ntucmap.getMap() ? null : map);
Can't you do something like this?
function clearMap(map) {
for(var i = 0; i<ntucmap.length; i++){
ntucmap[i].setMap(null);
}
}
and for the show part
function setMapOnAll(map) {
for (var i = 0; i < ntucmap.length; i++) {
ntucmap[i].setMap(map);
}
}
Then to have it in one button you can keep a counter with your button and when it's even do one function when it's odd do the other?
// Adds a marker at the center of the map.
var ntuc = {lat: 1.32805676, lng: 103.9216584};
addMarker(ntuc);
setMapOnAll(null);
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: 'https://maps.google.com/mapfiles/kml/paddle/blu-stars.png'
});
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);
}
}
// Show/Hide Markers
var counter = 0;
function toggleMarkers() {
if (counter == 0) {
setMapOnAll(map);
counter = 1;
} else {
setMapOnAll(null);
counter = 0;
}
}
In the end, I used array to save all the markers. Based on the button which user used to toggle, it will determine whether it marker(s) will be shown on the map or not.

Marker Google Maps Show/Hide OnClick

I am trying to make google maps project, I was showing my marker on my map.
But now I want to make show/hide marker when I click checkbox,
this my code for showing marker in my maps, data for my marker I get from MySQL,
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: (lat,long)
});
var infowindow = new google.maps.InfoWindow({});
var latArea = new Array();
var longArea = new Array();
for (i = 0; i < $$; i++) //looping until all data from mysql
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArea[i], longArea[i]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<b>Coordinat : </b>'+String(latArea[i])+' , '+
String(longArea[i]));
infowindow.open(map, marker);
}
})(marker, i));
}
}
I was successfully displaying all data to marker in maps and add function for hide/show marker but only one marker is hide/show not all,
this my code for show/hide function
function toggleMarker() {
if (!marker.getVisible()) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
Thank you.
i was solving this problem,
this is correct code,
<script>
var markers = new Array();
function initialize() {
var latArea = new Array();
var longArea = new Array();
var i, newMarker;
for (i = 0; i < $$; i++)
{
newMarker = new google.maps.Marker({
position: new google.maps.LatLng(latArea[i], longArea[i]),
map: map,
icon: icon,
newMarker.category = 'show';
newMarker.setVisible(false);
markers.push(newMarker);
}
}
function displayMarkers(obj,category) {
var i;
for (i = 0; i < $$; i++)
{
if (markers[i].category === category) {
if ($(obj).is(":checked")) {
markers[i].setVisible(true);
} else {
markers[i].setVisible(false);
}
} else {
markers[i].setVisible(false);
}
}
}
and this checkbox in html for show/hidden marker
<input type="checkbox" onclick="displayMarkers(this,'area');" />

How can I show markers text when I click on any marker

I am creating a google maps page. I am dynamically adding markers through a loop. I want to display when I click on any marker. How can I achieve that? This is my loop.
if(data.STATUS == STATUS.SUCCESS){
console.log("Markers Received");
deleteMarkers();
for(var i=0; i<data.DATA.length; i++){
addMarker({lat: data.DATA[i].LATITUDE, lng: data.DATA[i].LONGITUDE},data.DATA[i].INCIDENT);
}
}
function deleteMarkers() {
clearMarkers();
markers = [];
}
function addMarker(location,incident) {
var marker = new google.maps.Marker({
position: location,
map: map,
title: incident
});
markers.push(marker);
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function deleteMarkers() {
clearMarkers();
markers = [];
}
function clearMarkers() {
setMapOnAll(null);
}
function showMarkers() {
setMapOnAll(map);
}
First of all I delete all the markers by this function. And then reset them. This call runs after every minute. I want to display the incident when ever I click on the marker. How can I achieve that?
Hope, this helps.
var obj = {
infoWindow: new google.maps.InfoWindow(),
marker: new google.maps.Marker({
map: map,
position: latLngObj,
title: 'info name'
})
};
google.maps.event.addListener(obj.marker, 'click', function() {
obj.infoWindow.setContent("<div><b>" + obj.marker.title + "(" + distance + ")</b></div>");
obj.infoWindow.open(map, obj.marker);
});

JavaScript multidimensional array cannot access as array, only as string

I am trying to put multiple markers on a Google map. I have JS that builds an array and passes it to the Google function that handles markers.
Problem is, when I try to access the supposed array, I just get the first character as if it's a string.
$(document).ready(function () {
// initialize map to center on florida.
initializeGMap();
var locations = [];
#foreach (var item in Model)
{
<text>
locations.push(#Html.Raw(Json.Encode("'" + item.Name + "'," + item.Location.Latitude + "," + item.Location.Longitude + "")));
</text>
}
addMarker(locations);
});
I've tried several (read: 20+) variations of this including JSON.stringify it before sending, after sending, etc. Here's the function it gets passed too:
function addMarker(locations) {
var locations = JSON.stringify(locations);
alert(locations + '\n' + locations[0][0] + '\n' + locations[0][1]);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
alert("done");
}
When it gets to the line with 'locations[x][x]' all I ever get back in '[' which is the first character of the JSON string. It's not being treated at an array.
What am I missing?
I solved it via:
$(document).ready(function () {
// initialize map to center on florida.
initializeGMap();
// serialize model locations
var locationsToPass = #Html.Raw(Json.Encode(Model.Select(x => new { x.Name, x.Location.Latitude, x.Location.Longitude })));
addMarker(locationsToPass);
});
and in the receiving function:
function addMarker(locations) {
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].Latitude, locations[i].Longitude),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].Name);
infowindow.open(map, marker);
}
})(marker, i));
}
}
The key to troubleshooting was using this to detect if I was passing an array or not:
variable.constructor === Array
which I got here.

Recalculate markercluster onclick of filter

JS FIDDLE HERE:
http://jsfiddle.net/useyourillusiontoo/g77np63c/1/
I've created a google map that plants markers down and allows my to filter then with checkboxes without the page or map reloading. Yay!
Next I added marker cluster which worked too. However, when I now click on my markers the cluster doesn't update. That is.. the number inside the cluster doesnt change to reflect markers that are being hidden/displayed.
When I zoom in the markers are still being hidden/displayed but its just the cluster doesn't show this when zoomed out.
I've pasted my code below and would love any advice because i've been scratching my head.
var map;
var infowindow;
var image = [];
var gmarkers = [];
var clusterMarkers = [];
function mapInit(){
var centerCoord = new google.maps.LatLng(53.01265600000,-1.466105200000);
var mapOptions = {
zoom: 6,
center: centerCoord,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
addLocation();
var markerCluster = new MarkerClusterer(map, clusterMarkers);
function addLocation(place,category) {
for (var x in points){
var development = points[x];
var location = new google.maps.LatLng(development.lat, development.lng);
storeMarker(location, development);
}
}
function storeMarker(location, development){
var latLng = location;
var storedmarker = new google.maps.Marker({
position: latLng
});
storedmarker.mycategory = development.tid;
google.maps.event.addListener(storedmarker, 'click', function() {
if(typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: "<h3>"+ development.name +"</h3><a href='http://www.bbc.co.uk'>Show more!</a>"
});
infowindow.open(map, storedmarker);
});
clusterMarkers.push(storedmarker);
}
function show(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(true);
}
}
document.getElementById(category+"box").checked = true;
}
function hide(category) {
for (var i=0; i<clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
clusterMarkers[i].setVisible(false);
}
}
document.getElementById(category+"box").checked = false;
infowindow.close();
}
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}
jQuery(document).ready(function($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
}
jQuery(document).ready(function(){
mapInit();
});
added markers as requested. They are a basic JSON object
var points = [
{"name":"House","lat":"53.341265600000","lng":"- 1.466105200000","tid":"1"},
{"name":"Old house","lat":"53.361066200000","lng":"-1.465752700000","tid":"2"}]
setting the visible-property will not have an effect when a marker is inside a cluster, you must also remove/add the marker from/to the markerclusterer.
Possible solution:
observe the visible_changed -event of the markers:
google.maps.event.addListener(storedmarker,'visible_changed',function(){
markerCluster[(this.getVisible())?'addMarker':'removeMarker'](this)
});
http://jsfiddle.net/doktormolle/g77np63c/4/
another(possibly better) approach(especially whene there are a lot of markers, because the solution above will force a redraw of the clusters for each affected marker):
First collect all affected markers and then use addMarkers/showMarkers to toggle them:
function toggle(category, show) {
var markers = [];
for (var i = 0; i < clusterMarkers.length; i++) {
if (clusterMarkers[i].mycategory == category) {
markers.push(clusterMarkers[i]);
clusterMarkers[i].setVisible(show);
}
}
if (markers.length) {
markerCluster[(show) ? 'addMarkers' : 'removeMarkers'](markers);
}
if (!show && infowindow) infowindow.close();
}
function boxclick(box, category) {
toggle(category, box.checked);
}
jQuery(document).ready(function ($) {
$('.b2bfilter').click(function () {
boxclick(this, this.value);
});
});
http://jsfiddle.net/doktormolle/g77np63c/5/

Categories