Remove google maps markers that are in object array - javascript

I have markers that are stored in an object array and I cannot figure out how to delete them.
// Initialize Object Array
var Calls = [{
lat: 42,
lng: -72
}, {
lat: 40.7127837,
lng: -74.0059413
}, {
lat: 40.735657,
lng: -74.1723667
}];
// Initialize Map
function initMap()
{
map = new google.maps.Map(document.getElementById('map'),
{
center: Calls[0],
zoom: 14,
scaleControl: true
})
}
// Add Markers
function initMarkers()
{
for (var i = 0; i < Calls.length; i++)
{
var marker = new google.maps.Marker({
position: Calls[i],
map: map
});
}
}
// Start on Load
window.onload = function()
{
initMap();
initMarkers();
}
//Clear Markers
function clearOverlays()
{
initMarkers(null);
}
// Run Clear Markers Function every 3 seconds
setInterval(function()
{
clearOverlays();
Calls = [];
}, 3000)

Working fiddle.
You have to store markers in other array like :
var markers = [];
for (var i = 0; i < Calls.length; i++)
{
var marker = new google.maps.Marker({
position: Calls[i],
map: map
});
markers.push(marker);
}
After that add function that clear map from all markers :
function clearMap() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
Hope this helps.

Related

Cannot remove markers from google maps api

The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}

How to open web links from some Google Maps markers?

I can open web link from marker by
google.maps.event.addListener(marker, "click", function() {
window.open('http://example.com/');
});
But what if I need to place 100 markers with 100 links to Google Maps?
My array with coordinates and links looks like this
var point = [[52.7081444444445, 58.6677361111111, "Sib/2377/index.html"],
[52.7039611111111, 58.668425, "Sib/2378/index.html"],
[52.6993166666667, 58.6680305555556, "Sib/2379/index.html"],
[52.6946277777778, 58.6679416666667, "Sib/2380/index.html"],
[52.6947833333333, 58.6755555555556, "Sib/2381/index.html"]];
add the URL as a property of the marker (.url). Open the window using this.url
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
}
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: -33.9,
lng: 151.2
}
});
setMarkers(map);
}
// Data for the markers consisting of a Latitude, a Longitude and a URL.
var points = [
[52.7081444444445, 58.6677361111111, "http://www.google.com"],
[52.7039611111111, 58.668425, "http://www.yahoo.com"],
[52.6993166666667, 58.6680305555556, "http://maps.google.com"],
[52.6946277777778, 58.6679416666667, "http://maps.google.com?q=52.6946277777778,58.6679416666667"],
[52.6947833333333, 58.6755555555556, "http://maps.google.com?q=52.6947833333333,58.6755555555556"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

method fitBounds() only zooms to single marker

I have rendered a map with markers, which are saved as long lat values in a local xlsx file.
My aim is to automatically zoom to all markers, which are loaded via an input file button. For this I am using the fitbounds() method from googlemaps API.
Partial Example
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//create global infoWindow object
var infoWindow = new google.maps.InfoWindow();
var i, newMarker;
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
}
}
};
reader.readAsArrayBuffer(f);
}
But if I run my html file, it zooms just to one marker. I suppose that it is the first marker of the gmarkers array.
However I want to achieve following result, with the full extent of my uploaded marker:
In my main.html you can see my initMap() function and the function which is called if the document is ready. In the document ready function the handlefunction () is called.
var map;
//Change event to dropdownlist
$(document).ready(function(){
a = $('#input-id').fileinput({
'showUpload': false,
'showPreview': false,
'showCaption': false
});
a.change(handleFile);
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 48.7758459, lng: 9.1829321},
zoom: 3,
mapTypeControl: false
});
}
You have a typo in your code. Move the initialization of the bounds outside the loop.
for (var i=0; i < gmarkers.length; i++) {
bounds = new google.maps.LatLngBounds();
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
should be:
bounds = new google.maps.LatLngBounds();
for (var i=0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
proof of concept fiddle
code snippet:
var result = [{
Latitude: 37.4419,
Longitude: -122.1419
}, {
Latitude: 37.44,
Longitude: -122.14
}, {
Latitude: 40.44,
Longitude: -75.14
}]
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var gmarkers = [];
//loop over json format
for (i = 0, length = result.length; i < length; i++) {
var data = result[i];
//extract Lat Long values from result
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
//creating a marker and putting it on the map
newMarker = new google.maps.Marker({
position: latLng,
map: map
});
gmarkers.push(newMarker);
}
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < gmarkers.length; i++) {
loc = new google.maps.LatLng(gmarkers[i].position.lat(), gmarkers[i].position.lng());
bounds.extend(loc);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
This is another approach for your problem within 35 lines of code.
Make sure you pass the JSON object the right way and that you declare your classes within the appropriate lexical scope.
Make sure the JSON Object returns something like this:
const coords = [
{lat: 42.4, lng: 1.55},
{lat: 43.42, lng: 2.48},
{lat: 45.43, lng: 4.9}
];
Note I have changed result to a more meaningful coords array of objects.
// Create your markers without worrying about scope and without extensive For Loops
const markers = coords.map((coord) => {
return new google.maps.Marker({
position: new google.maps.LatLng(coord.lat, coord.lng),
map: map,
animation: google.maps.Animation.DROP
});
})
// Declare your bounds outside the map method (previous for loop)
const bounds = new google.maps.LatLngBounds();
// Iterate through markers and return coords for expanded viewport
markers.forEach((loc) =>{
loc = new google.maps.LatLng(loc.position.lat(), loc.position.lng());
return bounds.extend(loc);
});
map.fitBounds(bounds);
}

How to panTo a marker once a marker drops (Google Maps API)?

I would like to zoom into each marker on load once a marker drops onto the Google map.
I tried using the panTo and setZoom method inside the drop function and the addMarkerWithTimeout function, but it doesn't seem to work. I have spent the past couple hours trying to solve this issue. Does anyone have any ideas?
var neighbors = [
{lat: 41.081445, lng: -81.519005},
{lat: 42.652579, lng: -73.756232},
{lat: 61.218056, lng: -149.900278},
{lat: 32.735687, lng: -97.108066},
];
var markers = [];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('googlemapsbackground'), {
zoom: 4,
center: {lat: 39.8282, lng: -98.5795}
});
}
window.onload = function drop() {
clearMarkers();
for (var j = 0; j < neighbors.length; j++) {
addMarkerWithTimeout(neighbors[j], j * 1000);
}
}
function addMarkerWithTimeout(position, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
animation: google.maps.Animation.DROP
}));
}, timeout);
}
function clearMarkers() {
for (var j = 0; j < markers.length; j++) {
markers[j].setMap(null);
}
markers = [];
}
You can try utilizing a LatLngBounds object.
function addMarkerWithTimeout(position, timeout) {
window.setTimeout(function() {
var bounds = new google.maps.LatLngBounds(),
marker = new google.maps.Marker({
position: position,
map: map,
animation: google.maps.Animation.DROP
});
bounds.extend(marker.getPosition());
markers.push(marker);
map.fitBounds(bounds);
}, timeout);
}

show JSON parsed data in javascript loop for maps markers

I'm trying to get the markers longitude and latitude and display them on the map but I'm not getting any result, my parser.php file is working and fetching the data from the database i just need to format it into javascript
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: -25.363882, lng: 131.044922},
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.getJSON('parser.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon);
})(items[i]);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
parser.php output
[{"0":"33.880561","lat":"33.880561","1":"35.542831","lon":"35.542831"},{"0":"-25.363882","lat":"25.363882","1":"131.044922","lon":"131.044922"}]
Your problem is that the lat and lon values from your PHP are strings. I'm assuming (because your question doesn't include it at this stage) your addMarker function isn't converting those strings to the numeric objects that the google Maps expects for lat/lng values.
Try simply wrapping those in parseFloat() before passing them to the Maps API, e.g.
addMarker(parseFloat(item.lat), parseFloat(item.lon));
Alternatively you could do this in the addMarker function itself (which is probably better).
You need to add the marker to the map. The way your code is currently structured the map is local to the initialize function and there is no way to pass that value to the addMarker function.
You have two options:
pass the "map" variable into the addMarker function
function initialize() {
var mapOptions = {
center: {
lat: -25.363882,
lng: 131.044922
},
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.getJSON('parser.php', function (items) {
for (var i = 0; i < items.length; i++) {
(function (item) {
addMarker(item.lat, item.lon, map);
})(items[i]);
}
});
}
proof of concept fiddle
working code snippet:
function initialize() {
var mapOptions = {
center: {
lat: -25.363882,
lng: 131.044922
},
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// $.getJSON('parser.php', function (items) {
var items = [{
"0": "33.880561",
"lat": "33.880561",
"1": "35.542831",
"lon": "35.542831"
}, {
"0": "-25.363882",
"lat": "25.363882",
"1": "131.044922",
"lon": "131.044922"
}];
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, map);
})(items[i]);
}
// });
}
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, map) {
var latlng = new google.maps.LatLng(lat, lng);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
map.fitBounds(bounds);
return marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
make the "map" variable global.
var map; // global variable, outside of any function definition
function initialize() {
var mapOptions = {
center: {
lat: -25.363882,
lng: 131.044922
},
zoom: 14
};
// initialize the global variable (no "var")
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.getJSON('parser.php', function (items) {
for (var i = 0; i < items.length; i++) {
(function (item) {
addMarker(item.lat, item.lon);
})(items[i]);
}
});
}
working code snippet:
var map;
function initialize() {
var mapOptions = {
center: {
lat: -25.363882,
lng: 131.044922
},
zoom: 14
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// $.getJSON('parser.php', function (items) {
var items = [{
"0": "33.880561",
"lat": "33.880561",
"1": "35.542831",
"lon": "35.542831"
}, {
"0": "-25.363882",
"lat": "25.363882",
"1": "131.044922",
"lon": "131.044922"
}];
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon);
})(items[i]);
}
// });
}
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
map.fitBounds(bounds);
return marker;
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

Categories

Resources