I am trying to display markers on Google Maps which refresh periodically.
I found this piece of code which will add them to the map but I need to know how to delete them every refresh so that it stops displaying on the map when they are no longer in the xml file.
< script >
var map = null;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(53.3478, -6.2597) //center over dublin
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
loadXMLFile();
}
function loadXMLFile() {
var filename = 'data.xml';
$.ajax({
type: "GET",
url: filename,
dataType: "xml",
success: parseXML,
error: onXMLLoadFailed
});
function onXMLLoadFailed() {
alert("An Error has occurred.");
}
function parseXML(xml) {
var bounds = new google.maps.LatLngBounds();
$(xml).find("marker").each(function() {
//Read the name, address, latitude and longitude for each Marker
var nme = $(this).find('name').text();
var address = $(this).find('address').text();
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var markerCoords = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
bounds.extend(markerCoords);
var marker = new google.maps.Marker({
position: markerCoords,
map: map
});
});
map.fitBounds(bounds);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
< /script>
This works great when new markers are added by calling the function loadXMLFile() but if they are removed then they stay on the map. I think I need to remove them https://developers.google.com/maps/documentation/javascript/examples/marker-remove but I don't know how to apply this.
This has been driving me nuts for days. Can anyone help me out?
EDIT:
My full code is not rendering the map:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map-canvas {
height: 400px;
margin-bottom: 10px;
} }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
var markers = [];
function initialize() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(59.76522, 18.35002)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addDomListener(document.getElementById('add-markers'), 'click', addMarkers);
google.maps.event.addDomListener(document.getElementById('remove-markers'), 'click', removeMarkers);
}
function addMarkers() {
var coords = [
new google.maps.LatLng(59.32522, 18.07002),
new google.maps.LatLng(59.45522, 18.12002),
new google.maps.LatLng(59.86522, 18.35002),
new google.maps.LatLng(59.77522, 18.88002),
new google.maps.LatLng(59.36344, 18.36346),
new google.maps.LatLng(59.56562, 18.33002)];
for (var i = 0; i < coords.length; i++) {
var marker = new google.maps.Marker({
map: map,
position: coords[i]
});
markers.push(marker);
}
}
function removeMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
initialize();
</script>
</head>
<body>
<div id="map-canvas"></div>
<button id="add-markers">Add markers</button>
<button id="remove-markers">Remove markers</button>
</body>
</html>
1) Create an array to hold your markers
var markers = [];
2) Push each marker to the array when you add them to the map
var marker = new google.maps.Marker({
position: markerCoords,
map: map
});
markers.push(marker);
3) When you need to remove them, iterate through your array and call setMap(null) on each marker
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
Hope this helps.
JSFiddle demo
Edit:
Here is your code updated with my modifications. I guess you periodically call the loadXMLFile() function (?).
var map = null;
var markers = [];
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(53.3478, -6.2597) //center over dublin
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
loadXMLFile();
}
function loadXMLFile() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
var filename = 'data.xml';
$.ajax({
type: "GET",
url: filename,
dataType: "xml",
success: parseXML,
error: onXMLLoadFailed
});
function onXMLLoadFailed() {
alert("An Error has occurred.");
}
function parseXML(xml) {
var bounds = new google.maps.LatLngBounds();
$(xml).find("marker").each(function () {
//Read the name, address, latitude and longitude for each Marker
var nme = $(this).find('name').text();
var address = $(this).find('address').text();
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var markerCoords = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
bounds.extend(markerCoords);
var marker = new google.maps.Marker({
position: markerCoords,
map: map
});
markers.push(marker);
});
map.fitBounds(bounds);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Related
I've created a file that loads markers into a Google Maps JavaScript API canvas.
The markers are generated from an XML file, which get's the markers info from SQL.
I want to be able to call a function ex. loadMarkers() so that I can update the markers position when the SQL data has changed.
As of now, I could call load() again, but then it refreshes the whole map, and not just the markers. Just like a hard refresh of the site..
How can I wrap the code for just inserting markers, so that I can call it back as a function?
<!DOCTYPE html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
var customIcons = {
user: {
icon: 'http://maps.google.com/mapfiles/kml/shapes/man.png'
},
store: {
icon: 'http://maps.google.com/mapfiles/kml/shapes/grocery.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(59.914045, 10.756808),
zoom: 12,
mapTypeId: 'roadmap',
mapTypeControl: false,
streetViewControl: false,
zoomControl: false,
fullscreenControl: false
});
// here I want a function that pushes the markers by calling ex. setMarkers() function, that can be called later by setInterval(function() {setMarkers();},3000) to update markers location if the xml is changed
downloadUrl("xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
draggable: false,
animation: google.maps.Animation.DROP,
});
} // for each markers
}); //download url
} // load();
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
**//This is the function I want to update the markers with, without having to do a hard refresh of the site.**
setInterval(function() {setMarkers();},3000);
</script>
</head>
<body onload="load()">
<div id="map"></div>
</body>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<?php echo $api_key; ?>&callback=initMap">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js sensor=false"></script>
</html>
create a function (setMarkers) that does the downloadUrl call to load the XML and create markers on the map.
make the map variable global or pass it in to that function
create a global array to track those markers so you can remove them before loading the new ones.
var gmarkers = [];
function setMarkers() {
downloadUrl(urlString, function(data) {
var xml = data.responseXML;
for (var i=0; i<gmarkers.length; i++)
gmarkers[i].setMap(null);
gmarkers = [];
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
draggable: false,
animation: google.maps.Animation.DROP,
});
gmarkers.push(marker);
} // for each markers
}); //download url
}
call that function in the load function and in the setTimeout.
var map;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(59.914045, 10.756808),
zoom: 12,
mapTypeId: 'roadmap',
mapTypeControl: false,
streetViewControl: false,
zoomControl: false,
fullscreenControl: false
});
setMarkers();
} // load();
setInterval(function() {
setMarkers();
},3000);
working example
I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
I try to display multiple markers on my map. I put the multiples location in adata-attribute trough my php file. Then I try to grab this information in my javascript one.
If I directly paste the coordinates, the markers appear. If I reference the data-attribute they don't. (The only difference is on the line beginning with var locations.)
This code works:
function GoogleMapsInit(){
setTimeout(function initialize() {
var emplacements = $('#iframecarte').attr("data-emplacements");
// Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(45.5580421, -73.7303025)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = [[45.5314817,-73.1835154], [45.570004,-73.448701] ];
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
}, 500);
}
This one doesn't:
function GoogleMapsInit(){
setTimeout(function initialize() {
var emplacements = $('#iframecarte').attr("data-emplacements");
// Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(45.5580421, -73.7303025)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = emplacements;
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
}, 500);
}
What is wrong with the variable locations when it references the emplacements variable so that the markers don't show?
The non-working version emplacements is a string, not an array.
Convert the string to a javascript array:
var locations = JSON.parse(emplacements);
proof of concept fiddle
code snippet:
function GoogleMapsInit() {
setTimeout(function initialize() {
var emplacements = $('#iframecarte').attr("data-emplacements");
// Emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ]
var mapOptions = {
zoom: 9,
center: new google.maps.LatLng(45.5580421, -73.7303025)
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = JSON.parse(emplacements);
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
}, 500);
}
GoogleMapsInit();
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
<div id="iframecarte" data-emplacements="[[45.5314817,-73.1835154], [45.570004,-73.448701], [45.6066487,-73.712409]]"></div>
i was trying to use google map api v3 and pop up some markers on the map. un fortunately it doesnt show up on my map. i use array push to store marker with latitude and longitude parameter.
here is my code
<script type="text/javascript">
var trackerMarkerArray = [];
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myLatlng2 = new google.maps.LatLng(-25.363800,131.044900);
var mapOptions = {
center: myLatlng,
zoom: 8
};
try {
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng
});
var marker2 = new google.maps.Marker({
position: myLatlng2
});
trackerMarkerArray.push(marker);
trackerMarkerArray.push(marker2);
for (var i = 0; i<trackerMarkerArray.lenght; i++){
trackerMarkerArray[i].setMap(map);
console.log("value" + trackerMarkerArray[i]);
}
} catch (err){
alert(err);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
for (var i = 0; i<trackerMarkerArray.lenght; i++)
lenght must be "length"
also, when the map is not showing, try to see browser's debug console for any error.
I have this script for links from google map markers:
<script type="text/javascript">
var locations = [['Test 1','55','13','url1'],['Test 2','45','17','url2']];
function initialize()
{
var myOptions = {
center: new google.maps.LatLng(50,15),
zoom: 3,
mapTypeId: google.maps.MapTypeId.SATELLITE};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
setMarkers(map,locations)
}
function setMarkers(map,locations)
{
var marker, i
for(i = 0; i < locations.length; i++)
{
var arr = i
var name = locations[i][0]
var lat = locations[i][1]
var long = locations[i][2]
var adress = locations[i][3]
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map,
title: name,
url: adress,
position: latlngset
});
google.maps.event.addListener(marker, 'click', function() {window.location.href = this.url;});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
...and, I need generate infowindows from markers instead of links, do you have any simple idea?
Google map clickable infowindows from markers