I want to mark some data on google map.
I use eclipse Java EE and xml file is in the same workspace;(workspace_jsp).
xml file:
<csv_data>
<row>
<time>10:01:43</time>
<latitude>37.4805016667</latitude>
<longitude>126.952741667</longitude>
<pdistance>0.000555</pdistance>
<totaldistance>0.000555</totaldistance>
<sectionspray>3343.0</sectionspray>
</row>
<row>
<time>10:01:57</time>
<latitude>37.4807483333</latitude>
<longitude>126.952753333</longitude>
<pdistance>0.027396</pdistance>
<totaldistance>0.027951</totaldistance>
<sectionspray>3320.0</sectionspray>
</row>
my code is
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=~~~~"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.466285,126.948366),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("mark_info.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("/csv_data/row");
for (var i = 0; i < markers.length; i++) {
var time = markers[i].getAttribute("time");
var ss = markers[i].getAttribute("sectionspray");
var pd = markers[i].getAttribute("pdistance");
var td = markers[i].getAttribute("totaldistance");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var html = "<b>" + time + "</b> <br/>" + ss + pd + td;
var icon = customIcons[pd] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 2500px; height: 1500px"></div>
</body>
</html>
map is loaded on browser(IE, CHrome) but marks and infowindow..
what is wrong and how can I fix it?? please help me..
Your xml is not formatted as xml attributes. You can't retrieve it using getAttribute. The data is the content of XML elements. I use a nodeValue function from geoxml3 to retrieve the text from the element. To get the element, you can use getElementsByTagName, which returns an array of elements, if there is only one, that will be [0].
var markers = xml.getElementsByTagName('row');
for (var i = 0; i < markers.length; i++) {
var time = nodeValue(markers[i].getElementsByTagName("time")[0]);
var ss = nodeValue(markers[i].getElementsByTagName("sectionspray")[0]);
var pd = nodeValue(markers[i].getElementsByTagName("pdistance")[0]);
var td = nodeValue(markers[i].getElementsByTagName("totaldistance")[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markers[i].getElementsByTagName('latitude')[0])),
parseFloat(nodeValue(markers[i].getElementsByTagName('longitude')[0])));
var html = "<b>" + time + "</b> <br/>" + ss + pd + td;
var icon = customIcons[pd] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
proof of concept fiddle
code snippet:
var map;
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function initialize() {
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 infoWindow = new google.maps.InfoWindow;
var bounds = new google.maps.LatLngBounds();
var xml = xmlParse(xmlData);
var markers = xml.getElementsByTagName('row');
for (var i = 0; i < markers.length; i++) {
var time = nodeValue(markers[i].getElementsByTagName("time")[0]);
var ss = nodeValue(markers[i].getElementsByTagName("sectionspray")[0]);
var pd = nodeValue(markers[i].getElementsByTagName("pdistance")[0]);
var td = nodeValue(markers[i].getElementsByTagName("totaldistance")[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markers[i].getElementsByTagName('latitude')[0])),
parseFloat(nodeValue(markers[i].getElementsByTagName('longitude')[0])));
console.log(point.toUrlValue(6));
var html = "<b>" + time + "</b> <br/>" + ss + pd + td;
var icon = customIcons[pd] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bounds.extend(point);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, "load", initialize);
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
/**
* Extract the text value of a DOM node, with leading and trailing whitespace trimmed.
*
* #param {Element} node XML node/element.
* #param {Any} delVal Default value if the node doesn't exist.
* #return {String|Null}
*/
var nodeValue = function(node, defVal) {
var retStr = "";
if (!node) {
return (typeof defVal === 'undefined' || defVal === null) ? null : defVal;
}
if (node.nodeType == 3 || node.nodeType == 4 || node.nodeType == 2) {
retStr += node.nodeValue;
} else if (node.nodeType == 1 || node.nodeType == 9 || node.nodeType == 11) {
for (var i = 0; i < node.childNodes.length; ++i) {
retStr += arguments.callee(node.childNodes[i]);
}
}
return retStr;
}
var xmlData = '<csv_data><row><time>10:01:43</time><latitude>37.4805016667</latitude><longitude>126.952741667</longitude><pdistance>0.000555</pdistance><totaldistance>0.000555</totaldistance><sectionspray>3343.0</sectionspray></row><row><time>10:01:57</time><latitude>37.4807483333</latitude><longitude>126.952753333</longitude><pdistance>0.027396</pdistance><totaldistance>0.027951</totaldistance><sectionspray>3320.0</sectionspray></row>';
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>
Related
I need to find all the locations near by the lat long and radius provided.I think I can achieve this by using geofence but I don't know how to proceed.I have the following data.
set of lat long and to get the location for radius within 5km for all the lat long by each.
Any one help how to start this.
Inputs I have:
lat long
33.450909, -112.073196
33.466210, -112.064620
33.451640, -112.099130
33.437160, -112.048400
33.480860, -112.082130
33.489950, -112.074700
Tried so far:
<!DOCTYPE html >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Creating a Store Locator on Google Maps</title>
<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 style="margin:0px; padding:0px;" onload="initMap()">
<div>
<label for="raddressInput">Search location:</label>
<input type="text" id="addressInput" size="15"/>
<label for="radiusSelect">Radius:</label>
<select id="radiusSelect" label="Radius">
<option value="50" selected>50 kms</option>
<option value="30">30 kms</option>
<option value="20">20 kms</option>
<option value="10">10 kms</option>
</select>
<input type="button" id="searchButton" value="Search"/>
</div>
<div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
<div id="map" style="width: 100%; height: 90%"></div>
<script>
var map;
var markers = [];
var infoWindow;
var locationSelect;
function initMap() {
var sydney = {lat: 33.450909, lng: -112.073196};
map = new google.maps.Map(document.getElementById('map'), {
center: sydney,
zoom: 11,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
searchButton = document.getElementById("searchButton").onclick = searchLocations;
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
locationSelect.appendChild(option);
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap">
</script>
</body>
</html>
Using the above I can able to point single point,But what I want is to get the location around each lat long provided above radius is 5 km
If you are already using Google Maps, then I think you can try with computeDistanceBetween.
This is a short example of how to use it. You just need to eliminate those distances greater than the radius you set.
var home = ['Store', new google.maps.LatLng(29.520130, -98.415542)];
var pts = [
['Client A', new google.maps.LatLng(29.5197902, -98.3867079)],
['Client B', new google.maps.LatLng(29.5165967, -98.4235714)],
['Client C', new google.maps.LatLng(29.5198805, -98.3676648)]
];
var dist = google.maps.geometry.spherical.computeDistanceBetween;
pts.forEach(function(pt) {
console.log(home[0] + ' to ' + pt[0] + ': ' + (dist(home[1], pt[1])).toFixed(10));
});
Using code that was posted on here, I'm trying to map markers from an XML file to a Google Map in a JSP using the Google Maps Javascript API V3.
My markers file has the following format:
<markers>
<marker>
<id>0</id>
<lat>53341428</lat>
<lng>-6246720</lng>
<name>Fenian Street</name>
<number>63</number>
</marker>
<marker>
<id>1</id>
<lat>53346637</lat>
<lng>-6246154</lng>
<name>City Quay</name>
<number>99</number>
</marker>
And the code is:
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'`enter code here`
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl( "markers.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = markers[i].getElementsByTagName("id")[0];
var point = new google.maps.LatLng(
parseFloat(markers[i].getElementsByTagName("lat")[0]),
parseFloat(markers[i].getElementsByTagName("lng")[0]));
var name = markers[i].getElementsByTagName("name")[0];
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
icon: image
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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();
}
function doNothing() {
}
</script>
When I load the page, I see an error in he console: InvalidValueError: setTitle: not a string
What am I doing wrong? The markers are not appearing on the map.
You are getting that error because "name" is not a string, it is an XML DOM object. There is a function nodeValue that can be used to get the string content out of an XML DOM element.
Also, your latitude and longitude are not valid, they are not in decimal degrees.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.3430347, -6.2550587),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// downloadUrl( "markers.xml", function(data) {
// var xml = data.responseXML;
var xml = xmlParse(xmlString);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//var id = markers[i].getElement("id");
var id = nodeValue(markers[i].getElementsByTagName("id")[0]);
var point = new google.maps.LatLng(
parseFloat(nodeValue(markers[i].getElementsByTagName("lat")[0])),
parseFloat(nodeValue(markers[i].getElementsByTagName("lng")[0])));
var name = nodeValue(markers[i].getElementsByTagName("name")[0]);
//var number = markers[i].getElementsByTagName("number");
var html = "<b>" + id + "</b> <br/>" + name;
var image = 'img.png';
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
position: point,
map: map,
title: ""+name /*,
icon: image */
});
marker.setMap(map);
bindInfoWindow(marker, map, infoWindow, html);
}
// });
}
where nodeValue was "borrowed" from geoxml3:
//nodeValue: Extract the text value of a DOM node, with leading and trailing whitespace trimmed
function nodeValue (node, defVal) {
var retStr="";
if (!node) {
return (typeof defVal === 'undefined' || defVal === null) ? '' : defVal;
}
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
};
working fiddle
I have some issues with Google maps api v3. I managed to create a map where new markers are displayed when the user drag the map. However, it do not delete the past markers. I have read many tutorials and thread (especially this one: Google Maps V3: Updating Markers Periodically) without success.
Here is my main page:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Développez avec les API Google Maps</title>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#map_canvas {
height: 100%;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function createXmlHttpRequest() {
try {
if (typeof ActiveXObject != 'undefined') {
return new ActiveXObject('Microsoft.XMLHTTP');
} else if (window["XMLHttpRequest"]) {
return new XMLHttpRequest();
}
} catch (e) {
changeStatus(e);
}
return null;
};
function downloadUrl(url, callback) {
var status = -1;
var request = createXmlHttpRequest();
if (!request) {
return false;
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
try {
status = request.status;
} catch (e) {
}
if (status == 200) {
callback(request.responseText, request.status);
request.onreadystatechange = function() {};
}
}
}
request.open('GET', url, true);
try {
request.send(null);
} catch (e) {
changeStatus(e);
}
};
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
var map;
function initialize() {
var latlng = new google.maps.LatLng(46.7, 2.5);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
downloadUrl("getPoi2.php", function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
}
});
/* Ici, on ajoute l'écouteur d'événement suite à un glisser / déposer */
google.maps.event.addListener(map, 'dragend', function() {
var bds = map.getBounds();
var South_Lat = bds.getSouthWest().lat();
var South_Lng = bds.getSouthWest().lng();
var North_Lat = bds.getNorthEast().lat();
var North_Lng = bds.getNorthEast().lng();
downloadUrl("getPoi.php?maxlat="+North_Lat+"&minlat="+South_Lat+"&minlong="+South_Lng+"&maxlong="+North_Lng, function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
}
});
});
}
function createMarker(lat, lng, titre){
var latlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: titre
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
And there is my getPoin.php:
<?php
$user = "root";
$password = "";
$host = "localhost";
$bdd = "citiesinvaders";
mysql_connect($host,$user,$password);
mysql_select_db($bdd) or die("erreur de connexion à la base
de données");
$sql = "SELECT * FROM location order by city desc limit 1";
$res = mysql_query($sql) or die(mysql_error());
$dom = new DomDocument('1.0', 'utf-8');
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
while ($result = mysql_fetch_array($res)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("city", $result["city"]);
$newnode->setAttribute("lat", $result["latitude"]);
$newnode->setAttribute("lng", $result["longitude"]);
}
$xmlfile = $dom->saveXML();
echo $xmlfile;
?>
Thank you for your help!
Keep track of the google.maps.Marker objects created, delete them before creating new ones.
var map;
var gmarkers = [];
/* Ici, on ajoute l'écouteur d'événement suite à un glisser / déposer */
google.maps.event.addListener(map, 'dragend', function() {
var bds = map.getBounds();
var South_Lat = bds.getSouthWest().lat();
var South_Lng = bds.getSouthWest().lng();
var North_Lat = bds.getNorthEast().lat();
var North_Lng = bds.getNorthEast().lng();
downloadUrl("getPoi.php?maxlat="+North_Lat+"&minlat="+South_Lat+"&minlong="+South_Lng+"&maxlong="+North_Lng, function(data) {
var xml = xmlParse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
// hide and delete the existing markers
for (var i=0; i<gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
for (var i = 0; i < markers.length; i++) {
createMarker(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")), markers[i].getAttribute('titre'));
}
});
});
function createMarker(lat, lng, titre){
var latlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: titre
});
// keep a reference to created markers so you can remove them
gmarkers.push(marker);
}
This is based on my understanding of your question... To clarify... When the map is moved the markers are placed over the old markers? A.K.A. They are 'doubling up' on map drag?
Create an array to hold the markers.
var markers = [];
Then, add the markers to the array in 'createMarker()' function. Also, check to see if a marker has already been created, and if so, do not recreate.
function createMarker(lat, lng, titre) {
for( marker in markers ) {
var coord = marker.getgetPosition();
if( coord.lat() == lat && coord.lng() == lng )
return;
}
var latlng = new google.maps.LatLng(lat, lng);
markers.push( new google.maps.Marker({
position: latlng,
map: map,
title: titre
}));
}
I created a google map with this code:
function load() {
var markersArray = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("getMapMarkers.php", function(data) {
var bounds = new google.maps.LatLngBounds();
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 brewID = markers[i].getAttribute("brewID");
//construct url
var breweryLink = "http://beerportfolio.com/breweryPage.php?id=" + brewID;
//create directions link
http://maps.google.com/maps?daddr=
var directionsLink = "http://maps.google.com/maps?daddr=";
directionsLink = directionsLink + markers[i].getAttribute("lat") +"," + markers[i].getAttribute("lng")
var html = "<b>"+name+" </b> <br/>" ;
html = html + "<br> <br>";
html = html + "(Click for Directions)";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
bounds.extend(point);
}
map.fitBounds(bounds);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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 getMapVisit()
{
alert("clearing overlays...");
clearOverlays();
return false;
}
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function doNothing() {}
When I try an delete the markers to re-load different ones, I cannot delete them off the map.
On button press I call getMapVisit() which then calls clearOverlays(), but clearOverlays() doesn't clear the map. In Chrome, when I inspect the element I get this error:
Uncaught ReferenceError: markersArray is not defined
The error is called on line 86 which is:
if (markersArray) {
I do not know why its not defined when its clearly initialized array at the top of load()
You need to define var markersArray = []; above the load function so it will be globally defined and will be accessible in all the functions .
I have a marker which has a dynamic position (i.e. updated periodically). When marker is clicked, an infowindow is shown but when marker position is updated, the infowindow gets automatically closed. I want that when marker position is updated, infowindow position should also get updated automatically. How to solve this.
P.S. :- infowindow contain a form which is editable by the user.
Problem : when user is editing/filling the form and marker position gets updated (form not submitted yet), then the form will get closed and user will lose his data.
<script type="text/javascript">
var map;
var lat_longs = new Array();
var geocoder = null;
var infoWindow = new google.maps.InfoWindow();
var trafficLayer = null;
var weatherLayer = null;
var markers = new Array();
var poi = new Array();
var fitMap = 0;
loc_array = new Array();
totUpdateOld = new Array();
ident = 0;
function showMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng('-0.57128','117.202148'),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
trafficLayer = new google.maps.TrafficLayer();
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
showCarPosition(function() {
fitMapToBounds();
});
}
function showCarPosition(){
if (markers.length>0){
ident = 2;
}
var car_icon;
jQuery.getJSON('<s:property value="jsonUrl"/>','', function(data) {
var arrayCar = data.listCar;
for (var i = 0; i < arrayCar.length; i++) {
var car = arrayCar[i];
var status = "";
var tanggal = "never";
var car_type = (car.type != "" || car.type != null)?' ('+car.type+')':'';
if(car.lastUpdate == null){
car_icon = ctx + 'web/img/car_black.png';
status = "Belum pernah kirim data";
}else if((not_active = (currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 30){ //diff in minute
car_icon = ctx + 'web/img/car_red.png';
status = convertMinute(not_active);
}else if((((currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 5) && (car.lastSpeed == 0)){ //diff in minute
car_icon = ctx + 'web/img/car_yellow.png';
status = "Berhenti";
}else
car_icon = ctx + 'web/img/car_green.png';
if(car.lastUpdate != null){
var splitDate = car.lastUpdate.split("T");
tanggal = splitDate[1]+" "+splitDate[0].split("-")[2]+"-"+bulan[parseInt(splitDate[0].split("-")[1])]+"-"+splitDate[0].split("-")[0];
}
var coordinate = new google.maps.LatLng(car.latitude, car.longitude);
var windowContent =[
'<div class="windowcontent"><ul class="nav infowindow nav-pills nav-stacked">',
'<li class="active">'+car.plate +car_type+' - '+ car.driverName +'</li>',
(status != null)?'<li>'+status+'</li>':'',
(car.phoneNumber != null)?'<li>Phone : ' + car.phoneNumber+ '</li>':'',
'<li>Last Temp : ' + car.lastTemp+ '</li>',
(parseInt(car.lastSpeed)>0)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
(car.type != "" || car.type != null)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
'<li>Last Connected : ' + tanggal+ '</li>',
'<li>'+((car.note != null)?car.note:'no notes')+'<li>',
'<div id="'+car.id+'"></div></ul>',
'<span id="'+car.id+'" onclick="editinfo(this, \''+car.note+'\');">Edit Note</span></div>']
.join('');
if (ident == 0){
var marker = createMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
});
loc_array[car.id] = i;
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}else{
if (car.totalUpdate > totUpdateOld[car.id]) {
var map_post = loc_array[car.id];
markers[map_post].setMap(null);
var marker = updateMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
}, map_post);
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}
}
totUpdateOld[car.id] = car.totalUpdate;
}
fitMapToBounds();
});
setTimeout("showCarPosition()",5000);
}
function createMarker(markerOptions) {
var marker = new MarkerWithLabel(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
function updateMarker(markerOptions,id) {
var marker = new MarkerWithLabel(markerOptions);
markers[id] = marker;
lat_longs[id] = marker.getPosition();
return marker;
}
function fitMapToBounds() {
var bounds = new google.maps.LatLngBounds();
if (fitMap == 0){
if (lat_longs.length>0) {
for (var i=0; i<lat_longs.length; i++) {
bounds.extend(lat_longs[i]);
}
map.fitBounds(bounds);
fitMap = 1;
}
}
}
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
infoWindow.open(map, marker);
});
}
jQuery(document).ready(function() {
showMap();
});
</script>
<div id="map_canvas" class="widgettitle" style="height:540px;"></div>
call this function when the marker position is changed .
infowindow.open(map,marker);
Put an onblur event handler on the text field that calls a halt to the repositioning.
Then when it is submitted and goes to the new point, restart it (if needed).