This question already has answers here:
Google Maps Api v3 - find nearest markers
(7 answers)
Closed 9 years ago.
I'm trying to create an application in php that displays several markers on google map and allow a user to get the nearest marker when he click anywhere on the map. I tried the following code. But its not working. Can anyone please help?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Javascript API v3 Example: Loading clustered data from an XML</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>
<style type="text/css">
html, body { height: 100%; }
</style>
<script type="text/javascript">
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
// map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(8.491118,76.949840),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(map, 'click', find_closest_marker);
downloadUrl("marker.xml", function(doc) {
map.markers = [];
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("Lat"));
var lng = parseFloat(markers[i].getAttribute("Longt"));
var point = new google.maps.LatLng(lat,lng);
var hname = markers[i].getAttribute("Hname");
var Phone = markers[i].getAttribute("Phone");
var html="<b>"+hname+"</b><br>"+Phone;
var marker = createMarker(point,hname+" "+Phone,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<gmarkers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
map.setCenter(gmarkers[closestMarker].getPosition());
if (map.getZoom() < 16) map.setZoom(16);
google.maps.event.trigger(gmarkers[closestMarker], 'click');
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" >
<div id="side_bar" style="width:300px;height:450px; text-decoration: underline; color: #4444ff; overflow:auto;"></div>
</td>
</tr>
</table>
</body>
</html>
marker.xml
<markers>
<marker Hname="CHC Anchuthengu" Lat="8.6734310" Longt="76.7581770"/>
<marker Hname="PHC Perumathura" Lat="8.6218640" Longt="76.7975220"/>
<marker Hname="PHC Keezhattingal" Lat="8.6982130" Longt="76.7915000"/>
<marker Hname="PHC Azhoor" Lat="8.6408080" Longt="76.8252470"/>
</markers>
You need to create the map.markers array (this part not tested):
downloadUrl("phpsqlajax_genxml.php", function(data) {
map.markers = [];
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var hname = markers[i].getAttribute("Hname");
var Phone = markers[i].getAttribute("Phone");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("Lat")), parseFloat(markers[i].getAttribute("Longt")));
var html = "<b>" + hname + "<br/>" + Phone + "</b>";
var type = "bar";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
map.markers.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
I would suggest using the geometry library computeDistanceBetween function
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<map.markers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
allert(map.markers[closestMarker].title);
}
working example
Related
i am using PHP & MYSQL on wordpress in order to retrieve data from the database that contains coordinates and display markers on the Google Map.
Markers are shown on the map with the info window contains the coordinates.
i want to retrieve more info from the database and includes it in the info window
in the debug mode it show the info that is i want to add to the info window when i uncomment it markers will not show.
code:
<?php
/*
Template Name: MAP2
*/
get_header();
?>
<!DOCTYPE html>
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=********&callback=initMap">
</script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 600px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map,currentPopup;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(33.888630, 35.495480),
mapTypeId: 'roadmap'
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
// i need to add here the info
//icon: icons[feature.type].icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: feature.position.toString(),
//or here the info
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
var features = [
<?php
global $wpdb;
$prependStr ="";
foreach( $wpdb->get_results("SELECT siteID, latitude, longitude FROM site_coordinates2", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$info = $row->siteID;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
// info:<?php echo $info;?>,
}
<?php
$prependStr =",";
}
?>
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
</script>
</body>
</html>
<?php
get_footer();
?>
where the AM001 is the first Site ID in the MYSQL databases
assuming that you want us sietID as info
var features = [
<?php
global $wpdb;
$prependStr ="";
foreach( $wpdb->get_results("SELECT siteID, latitude, longitude FROM site_coordinates2", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$info = $row->siteID;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
info:<?php echo $info;?>,
}
<?php
$prependStr =",";
}
?>
];
then in your var popup you should add the info text
var popup = new google.maps.InfoWindow({
content: feature.position.toString() + ' my info siteID: ' + feature.info ,
//or here the info
maxWidth: 300
});
I'm developing a mobile app that allows a user to record some data about their favourite monuments. Now, when a user takes a photo of their monument the lat and long values are instantly recorded. Giving me two separate values.
The user then syncs this data with my PostGreSQL database. I want to manipulate this data on my website service.
All I want is a simple map plugin which will take each (so like a foreach loop) record relating to a user (name of monument, lat and long) and display it on a map with icon markers.
So for example, you could have a favourite monument in Cardiff and one in London. You would have two markers displayed on your account map and when you click on their a pop-up says 'Cardiff Museum' and 'London Eye'.
I've tried multiple searches on Google but to no avail.
Has anyone ever implemented something similar? I'm good with either PHP or JQuery or both solutions!
Here is the code where you can pass multiple lat-long combinations to add a marker for each user location.
Repeat this code for every marker you need in your loop to traverse locations array.
t.push('Location Name 1');
x.push(33.84659); // you can write like x.push(<?php echo $userloc[0]['lat']?>)
y.push(-84.35686);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
The complete code is given below.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() { initialize(); });
function initialize() {
var map_options = {
center: new google.maps.LatLng(33.84659,-84.35686),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
var info_window = new google.maps.InfoWindow({
content: 'loading'
});
var t = [];
var x = [];
var y = [];
var h = [];
t.push('Location Name 1');
x.push(33.84659);
y.push(-84.35686);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
t.push('Location Name 2');
x.push(33.846253);
y.push(-84.362125);
h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');
var i = 0;
for ( item in t ) {
var m = new google.maps.Marker({
map: google_map,
animation: google.maps.Animation.DROP,
title: t[i],
position: new google.maps.LatLng(x[i],y[i]),
html: h[i]
});
google.maps.event.addListener(m, 'click', function() {
info_window.setContent(this.html);
info_window.open(google_map, this);
});
i++;
}
}
</script>
<div id="map_canvas" style="width:400px;height:400px;">Google Map</div>
This code may help you. You can see its working demo here(http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=-33.866603&lon=151.207108&setLatLon=Set)
<!-- Original script taken from: http://conversationswithmyself.com/googleMapDemo.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<style type="text/css">
<!--
h1 {
font-family:sans-serif;
color:blue;
text-align: center;
font-size:120%;
}
.tekst {
font-family:sans-serif;
color:blue;
font-size:100%;
}
.smalltekst {
font-family:sans-serif;
color:black;
font-size:80%;
}
-->
</style>
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAF4PVqw0p5l92pEmE39k0MRQWxhPw7-SAnMb84NfHs4vQ3HTp4BTb-yeL6fQg7Up9d9idBGy5naXydw" type="text/javascript"></script>
<title>Google Maps Latitude, Longitude Popup</title>
</head>
<body>
<h1>Google Maps Latitude, Longitude Popup</h1>
<div style="width: 600px;" class="tekst"><b>Simply click on the map on a location and it will provide you with the latitude and longitude in the callout window.</b></div>
<div id="map" style="width: 600px; height: 400px"></div>
<div id="geo" style="width: 300px;position: absolute;left: 620px;top: 100px;" class="tekst">
<form name="setLatLon" action="googleMapLocation.php">
<b>* Coordinates:</b><br />
<table>
<tr><td>* Lat:</td><td><input type='text' name='lat' id="frmLat"></td></tr>
<tr><td>* Lon:</td><td><input type='text' name='lon' id="frmLon"></td></tr>
</table>
<input type="submit" name="setLatLon" value="Set"><br />
</form><br />
<b>* Flickr tags:</b><br />
<textarea id="geocode" cols="30" rows="2"></textarea><br />
<br />
<b>* RoboGEO tags:</b><br />
<textarea id="geocodeRoboGEO" cols="30" rows="2"></textarea><br />
* Show location on Multimap<br />
* Permanent Link<br /><br />
<script type="text/javascript">
<!--
google_ad_client = "pub-1588116269263536";
google_alternate_color = "FFFFFF";
google_ad_width = 234;
google_ad_height = 60;
google_ad_format = "234x60_as";
google_ad_type = "text";
//2006-09-30: Map
google_ad_channel ="0993881556";
google_color_border = "DDDDDD";
google_color_bg = "DDDDDD";
google_color_link = "0000FF";
google_color_text = "333333";
google_color_url = "333333";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<div style="width: 600px;" class="smalltekst">
<p><i>Address lookup has been removed because it violated the ToS of Google Maps.</i></p>
Based on code taken from this website and this website.<br />
All other errors are caused by code written by Pierre Gorissen.<br />
</div>
<script type="text/javascript">
//<![CDATA[
var baseLink = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php";
var multimapBaseLink = "http://www.multimap.com/map/browse.cgi?scale=10000&icon=x";
var geocoder = new GClientGeocoder();
var setLat = 51.618017;
var setLon = 2.48291;
// argItems code taken from
// http://www.evolt.org/article/Javascript_to_Parse_URLs_in_the_Browser/17/14435/?format=print
function argItems (theArgName) {
sArgs = location.search.slice(1).split('&');
r = '';
for (var i = 0; i < sArgs.length; i++) {
if (sArgs[i].slice(0,sArgs[i].indexOf('=')) == theArgName) {
r = sArgs[i].slice(sArgs[i].indexOf('=')+1);
break;
}
}
return (r.length > 0 ? unescape(r).split(',') : '')
}
function getCoordForAddress(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address\n\n Sorry, dat adres bestaat blijkbaar niet!");
} else {
place = response.Placemark[0];
setLat = place.Point.coordinates[1];
setLon = place.Point.coordinates[0];
setLat = setLat.toFixed(6);
setLon = setLon.toFixed(6);
document.getElementById("frmLat").value = setLat;
document.getElementById("frmLon").value = setLon;
}
placeMarker(setLat, setLon)
}
function placeMarker(setLat, setLon) {
var message = "geotagged geo:lat=" + setLat + " geo:lon=" + setLon + " ";
document.getElementById("geocode").value = message;
var messageRoboGEO = setLat + ";" + setLon + "";
document.getElementById("geocodeRoboGEO").value = messageRoboGEO;
document.getElementById("geocode").focus();
document.getElementById("geocode").select();
document.getElementById("maplink").href = baseLink + "?lat=" + setLat + "&lon=" + setLon ;
document.getElementById("multimap").href = multimapBaseLink + "&lat=" + setLat + "&lon=" + setLon ;
document.getElementById("frmLat").value = setLat;
document.getElementById("frmLon").value = setLon;
var map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl()); // added
map.addControl(new GMapTypeControl()); // added
map.centerAndZoom(new GPoint(setLon, setLat), 12);
var point = new GPoint(setLon, setLat);
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(map, 'click', function(overlay, point) {
if (overlay) {
map.removeOverlay(overlay);
} else if (point) {
map.recenterOrPanToLatLng(point);
var marker = new GMarker(point);
map.addOverlay(marker);
var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( point );
if ( matchll ) {
var lat = parseFloat( matchll[1] );
var lon = parseFloat( matchll[2] );
lat = lat.toFixed(6);
lon = lon.toFixed(6);
var message = "geotagged geo:lat=" + lat + " geo:lon=" + lon + " ";
var messageRoboGEO = lat + ";" + lon + "";
} else {
var message = "<b>Error extracting info from</b>:" + point + "";
var messagRoboGEO = message;
}
marker.openInfoWindowHtml(message);
document.getElementById("geocode").value = message;
document.getElementById("geocodeRoboGEO").value = messageRoboGEO;
document.getElementById("geocode").focus();
document.getElementById("geocode").select();
document.getElementById("maplink").href = baseLink + "?lat=" + lat + "&lon=" + lon ;
document.getElementById("multimap").href = multimapBaseLink + "&lat=" + lat + "&lon=" + lon ;
document.getElementById("frmLat").value = lat;
document.getElementById("frmLon").value = lon;
}
});
}
function findAddress() {
myAddress = document.getElementById("address").value;
geocoder.getLocations(myAddress, getCoordForAddress);
}
if (argItems("lat") == '' || argItems("lon") == '') {
placeMarker(setLat, setLon);
} else {
var setLat = parseFloat( argItems("lat") );
var setLon = parseFloat( argItems("lon") );
setLat = setLat.toFixed(6);
setLon = setLon.toFixed(6);
placeMarker(setLat, setLon);
}
//]]>
</script>
<!-- Start twatch code -->
<script type="text/javascript"><!--
//<![CDATA[
document.write('<scr'+'ipt type="text/javascript" src="/Pierre/twatch/jslogger.php?ref='+( document["referrer"]==null?'':escape(document.referrer))+'&pg='+escape(window.location)+'&cparams=true"></scr'+'ipt>');
//]]>
//--></script>
<!-- End twatch code -->
</body>
</html>
I'd like to use google maps in an unconventional way. I want to execute the javacript but I do not want to render any images. Rather I want to send some data to a file, use some of the computational functions the API has to offer and then pass back a text response. I attempted this with the following code but I then realized this probably won't work as javascript is run in a browser and not as a remote web service. That being said, how could a remote server call a 'web service' much like the one my code below has to offer with the goal of getting the simple 'yes' or 'no' response.
<?php
// Get vars
$lat=$_GET["lat"];
$lon=$_GET["lon"];
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEYNOTYOURS:)&sensor=true&libraries=geometry">
</script>
<script type="text/javascript">
// Poygon getBounds extension - google-maps-extensions
// http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds = function(latLng) {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var p = 0; p < paths.getLength(); p++) {
path = paths.getAt(p);
for (var i = 0; i < path.getLength(); i++) {
bounds.extend(path.getAt(i));
}
}
return bounds;
}
}
// Polygon containsLatLng - method to determine if a latLng is within a polygon
google.maps.Polygon.prototype.containsLatLng = function(latLng) {
// Exclude points outside of bounds as there is no way they are in the poly
var bounds = this.getBounds();
if(bounds != null && !bounds.contains(latLng)) {
return false;
}
// Raycast point in polygon method
var inPoly = false;
var numPaths = this.getPaths().getLength();
for(var p = 0; p < numPaths; p++) {
var path = this.getPaths().getAt(p);
var numPoints = path.getLength();
var j = numPoints-1;
for(var i=0; i < numPoints; i++) {
var vertex1 = path.getAt(i);
var vertex2 = path.getAt(j);
if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) {
if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
inPoly = !inPoly;
}
}
j = i;
}
}
return inPoly;
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(38.990842,-76.93625),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var box = [new google.maps.LatLng(38.9913160,-76.937079),
new google.maps.LatLng(38.991333,-76.936119),
new google.maps.LatLng(38.990287, -76.936108),
new google.maps.LatLng(38.990278,-76.937057),
new google.maps.LatLng(38.990495,-76.937052),
new google.maps.LatLng(38.990499,-76.936424),
new google.maps.LatLng(38.991091,-76.93643),
new google.maps.LatLng(38.991104,-76.937079)
];
var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
var AVpoly = new google.maps.Polygon({path:box,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4});
var lat = <?php echo $lat; ?>;
var lon = <?php echo $lon; ?>;
if(AVpoly.containsLatLng(new google.maps.LatLng(lat,lon), box) == true) {
document.write("Yes");
}
else
{
document.write("No");
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
This is not allowed! You may only use Google Maps Data if you are displaying a map that is publicly accessible. See section 9.1 of the TOS and 10.1.1 (g) "No Use of Content without a Google Map.":
I'm stuck on a current issue when I'm trying to use the custom infobox with google API v3 PHP / SQL Database. I'm having the hardest time figuring out where I messed up, the div shows up blank instead of having a map. Any help would awesome!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript">
var customIcons = {
Clinic: {
icon: 'icon_2.png',
},
Secondary: {
icon: 'icon_1.png',
}
};
function initialize() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
scrollwheel: false,
mapTypeId: 'roadmap'
});
downloadUrl("xml.php", function(data) {
function createMarker(markerXML) {
var name = markerXML.getAttribute("name"),
postid = markers [i].getAttribute("post_id"),
address = markers[i].getAttribute("address"),
phone = markers[i].getAttribute("phone"),
listtype = markers[i].getAttribute("type"),
monday = markers[i].getAttribute("monday"),
tuesday = markers[i].getAttribute("tuesday"),
wednesday = markers[i].getAttribute("wednesday"),
thursday = markers[i].getAttribute("thursday"),
friday = markers[i].getAttribute("friday"),
saturday = markers[i].getAttribute("saturday"),
sunday = markers[i].getAttribute("sunday"),
type = markers[i].getAttribute("type"),
point = new google.maps.LatLng(
lat = parseFloat(markerXML.getAttribute("lat")),
lng = parseFloat(markerXML.getAttribute("lng")),
icon = customIcons[type] || {},
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
icon: icon.icon,
}),
boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "<b>" + name + "</b> <br/> <i>" + listtype + "</i> <br/>" + address + "<br/>" + phone + "<br/>" + monday + tuesday + wednesday + thursday + friday + saturday + sunday;
var myOptions = {
content: boxText,
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-140, 0),
zIndex: null,
boxStyle: {
background: "url('tipbox.gif') no-repeat",
opacity: 0.75,
width: "280px"
},
closeBoxMargin: "10px 2px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
var infoBox = new InfoBox(myOptions);
google.maps.event.addListener(marker, 'click', function () {
infoBox.open(map, marker);
}
});
}
var xml = data.responseXML,
markers = xml.documentElement.getElementsByTagName("marker"),
numMarkers = markers.length;
for (var i = 0; i < numMarkers; i++) {
createMarker(markers[i]);
}
});
}
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>
<div id="map_canvas" style="width: 500px; height: 300px"></div>
Look at the javascript console and fix the errors you find there. Just commenting out dowloadUrl call should get you your map back.
You didn't provide a sample of your xml, but the second step (after fixing your javascript errors) would be to open the xml feed in your browser and see if it is valid (or you could run it through an xml validator)
This article (which it looks like you might have started with) also provides some debugging suggestions.
working version
I started with https://developers.google.com/maps/articles/phpsqlajax_v3 and am using
https://developers.google.com/maps/articles/phpsqlsearch_v3 to try to dynamically filter the content from a mysql DB and update my markers based on the returned results.
My php returns a valid xml file so no worries there. I'm just not sure what I'm doing wrong for the clearing and creating the new markers from the new query.
The load() function gives me a nice new map with markers on it, but the form doesn't seem to do anything. I even tried just have the form button call clearLocations() and nothing happens. The screen kinda blinks but all the points stay there.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Property Sales</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var markersArr = [];
var map;
var infoWindow;
function updateMap(){
var maxbid = document.getElementById('maxbid').value;
var minbid = document.getElementById('minbid').value;
var salestatus = document.getElementById('salestatus').value;
var saledate = document.getElementById('saledate').value;
infoWindow = new google.maps.InfoWindow;
var queryString = "phpsqlajax_genxml3dynamic.php?maxbid=" + maxbid + "&minbid=" + minbid + "&salestatus=" + salestatus + "&saledate=" + saledate;
//var queryString = "phpsqlajax_genxml3dynamic.php?maxbid=" + maxbid + "&minbid=" + minbid;
queryString="phpsqlajax_genxml3dynamic.php?maxbid=340000&minbid=0&salestatus=*&saledate=*";
downloadUrl( queryString, function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
clearLocations();
for (var i = 0; i < markers.length; i++) {
var SaleDate = markers[i].getAttribute("SaleDate");
var CaseNumber = markers[i].getAttribute("CaseNumber");
var Address = markers[i].getAttribute("Address");
var ZipCode = markers[i].getAttribute("ZipCode");
var Plaintiff = markers[i].getAttribute("Plaintiff");
var Defendant = markers[i].getAttribute("Defendant");
var Attorney = markers[i].getAttribute("Attorney");
var SoldTo = markers[i].getAttribute("SoldTo");
var PID = markers[i].getAttribute("PID");
var Appraisal = markers[i].getAttribute("Appraisal");
var MinBid = markers[i].getAttribute("MinBid");
var SaleAmt = markers[i].getAttribute("SaleAmt");
var SaleStatus = markers[i].getAttribute("SaleStatus");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitude")),
parseFloat(markers[i].getAttribute("Longitude"))
);
var info = "<b>Sale Date:" + SaleDate +"<br/>Address:"+ Address+"<br/>Sale Amount:" + SaleAmt + "</b> <br/>Sale Date:" + SaleDate+ "<br/>Case Number:"+ CaseNumber+ "<br/>Address:"+ Addre\
ss+ "<br/>Zipcode:"+ ZipCode+ "<br/>Plaintiff:"+ Plaintiff+ "<br/>Defendant:"+ Defendant+ "<br/>Attorney:"+ Attorney+ "<br/>Sold to:"+ SoldTo+ "<br/>Parcel ID:"+ PID+ "<br/>Appraisal:"+ Appraisal+\
"<br/>Minimum bid:"+ MinBid+ "<br/>Sale amount:"+ SaleAmt+ "<br/> Sale status:"+ SaleStatus;
var icon = customIcons[SaleStatus] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, info);
markersArr.push(marker);
}
});
}
var customIcons = {
ACTIVE: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
CANCELLED: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_black.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
NOBIDNOSALE: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
SOLD: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markersArr[i].setMap(null);
}
markersArr.length = 0;
}
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39.7620028,-84.3542049),
zoom: 10,
mapTypeId: 'roadmap'
});
infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
// downloadUrl("phpsqlajax_genxml3.php", function(data) {
downloadUrl( "phpsqlajax_genxml3dynamic.php?maxbid=54,000&minbid=0&salestatus=*&saledate=*", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var SaleDate = markers[i].getAttribute("SaleDate");
var CaseNumber = markers[i].getAttribute("CaseNumber");
var Address = markers[i].getAttribute("Address");
var ZipCode = markers[i].getAttribute("ZipCode");
var Plaintiff = markers[i].getAttribute("Plaintiff");
var Defendant = markers[i].getAttribute("Defendant");
var Attorney = markers[i].getAttribute("Attorney");
var SoldTo = markers[i].getAttribute("SoldTo");
var PID = markers[i].getAttribute("PID");
var Appraisal = markers[i].getAttribute("Appraisal");
var MinBid = markers[i].getAttribute("MinBid");
var SaleAmt = markers[i].getAttribute("SaleAmt");
var SaleStatus = markers[i].getAttribute("SaleStatus");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("Latitude")),
parseFloat(markers[i].getAttribute("Longitude")));
var info = "<b>Sale Date:" + SaleDate +"<br/>Address:"+ Address+"<br/>Sale Amount:" + SaleAmt + "</b> <br/>Sale Date:" + SaleDate+ "<br/>Case Number:"+ CaseNumber+ "<br/>Address:"+ Addre\
ss+ "<br/>Zipcode:"+ ZipCode+ "<br/>Plaintiff:"+ Plaintiff+ "<br/>Defendant:"+ Defendant+ "<br/>Attorney:"+ Attorney+ "<br/>Sold to:"+ SoldTo+ "<br/>Parcel ID:"+ PID+ "<br/>Appraisal:"+ Appraisal+\
"<br/>Minimum bid:"+ MinBid+ "<br/>Sale amount:"+ SaleAmt+ "<br/> Sale status:"+ SaleStatus;
var icon = customIcons[SaleStatus] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, info);
markersArr.push(marker);
}
});
}
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()">
<form name='myForm'>
Min Bid $ :<input type='text' id='minbid' value='1,000' /> and
$ :<input type='text' id='maxbid' value='1,000,000' /> <br>
Sale Status:<select id='salestatus'>
<option value="*" selected>All</option>
<option>Active</option>
<option>Sold</option>
<option>Cancelled</option>
<option>No Bid, No Sale</option>
</select>
<br>
Sale Date:<select id='saledate'>
<option value="*" selected>All</option>
<option>2012-06-08</option>
<option>2012-06-01</option>
<option>2012-05-25</option>
<option>2012-05-18</option>
<option>2012-05-11</option>
<option>2012-05-04</option>
<option>2012-04-27</option>
<option>2012-04-20</option>
<option>2012-04-13</option>
<option>2012-04-06</option>
<option>2012-03-30</option>
<option>2012-03-23</option>
<option>2012-03-16</option>
<option>2012-03-09</option>
<option>2012-03-02</option>
</select>
<input type='button' onclick='updateMap()' value='Update Map' />
</form>
<div id="map" style="width: 95%; height: 85%"></div>
</body>
</html>
Again I'm 99.9% sure the php is fine since it returns valid results which are used to populate the field. I'm befuddled as to what I've done wrong for the update.
Hey SO this isn't spam let me post this dang question.
Your clearLocations function is looping over markers not markersArr which contains the existing marker references.
Should be
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markersArr.length; i++) {
markersArr[i].setMap(null);
}
markersArr.length = 0;
}