This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
i am using google map to create a dynamic google map that take locations(lat, lon) stored in the database using php mysql and display the selected locations by markers on the map
but the problem is that i get the map displayed with a blue color without anything else
if anyone can help me i will appreciate that
map.php
<?php
$conn = mysql_connect("localhost", "****", "*****") or die(mysql_error());
mysql_select_db("map") or die(mysql_error());
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 350px; height: 300px; border: 0px; padding: 0px; }
</style>
<script src="http://maps.google.com/maps/api/js?key=mykey&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: 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;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
});
<?php
$query = mysql_query("SELECT * FROM poi_example")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$name = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$desc = $row['desc'];
echo("addmarker($lat, $lon, '<b>$name</b><br />$desc');\n");
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
the database is
CREATE TABLE IF NOT EXISTS `poi_example` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`desc` text NOT NULL,
`lat` text NOT NULL,
`lon` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `poi_example`
--
INSERT INTO `poi_example` (`id`, `name`, `desc`, `lat`, `lon`) VALUES
(1, '100 Club', 'Oxford Street, London W1<br/>3 Nov 2010 : Buster Shuffle<br/>', '51.514980', '-0.144328'),
(2, '93 Feet East', '150 Brick Lane, London E1 6RU<br/>7 Dec 2010 : Jenny & Johnny<br/>', '51.521710', '-0.071737'),
(3, 'Adelphi Theatre', 'The Strand, London WC2E 7NA<br/>11 Oct 2010 : Love Never Dies', '51.511010', '-0.120140'),
(4, 'Albany, The', '240 Gt. Portland Street, London W1W 5QU', '51.521620', '-0.143394'),
(5, 'Aldwych Theatre', 'Aldwych, London WC2B 4DF<br/>11 Oct 2010 : Dirty Dancing', '51.513170', '-0.117503'),
(6, 'Alexandra Palace', 'Wood Green, London N22<br/>30 Oct 2010 : Lynx All-Nighter', '51.596490', '-0.109514');
This is how it should be (sorry for the indentation):
<?php
$conn = mysql_connect("localhost:4040", "xxxx", "xxxx") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 350px; height: 300px; border: 0px; padding: 0px; }
</style>
<script src="http://maps.google.com/maps/api/js?key=xxxxxxxxxxxxxxx&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: 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;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
});
<?php
$query = mysql_query("SELECT * FROM poi_example")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$name = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$desc = $row['desc'];
echo("addMarker($lat, $lon, '<b>$name</b><br />$desc');\n");
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
The issue is: addmarker in the call va addMarker in function definition (JS is case-sensitive)
Related
I'm facing a problem to display the random locations around the location are fetching from mysql, the method found Here. and its working prefect when i give value for lat and lng directly ,but in my code after using mysql data not able to display the random location on map ,google map displaying only the location from mysql as shown in the picture. so i wish someone can help me about my problem.
the result after run the code
the database and data define as:
CREATE TABLE IF NOT EXISTS `map` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`desc` text NOT NULL,
`lat` text NOT NULL,
`lon` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `map`
--
INSERT INTO `poi_example` (`id`, `name`, `desc`, `lat`, `lon`) VALUES
(1, '100 Club', 'Oxford Street, London W1<br/>3 Nov 2010 : Buster Shuffle<br/>', '51.514980', '-0.144328'),
(2, '93 Feet East', '150 Brick Lane, London E1 6RU<br/>7 Dec 2010 : Jenny & Johnny<br/>', '51.521710', '-0.071737'),
(3, 'Adelphi Theatre', 'The Strand, London WC2E 7NA<br/>11 Oct 2010 : Love Never Dies', '51.511010', '-0.120140'),
(4, 'Albany, The', '240 Gt. Portland Street, London W1W 5QU', '51.521620', '-0.143394'),
(5, 'Aldwych Theatre', 'Aldwych, London WC2B 4DF<br/>11 Oct 2010 : Dirty Dancing', '51.513170', '-0.117503'),
(6, 'Alexandra Palace', 'Wood Green, London N22<br/>30 Oct 2010 : Lynx All-Nighter', '51.596490', '-0.109514');
and the php file for displaying the map:
<?php
$conn = mysql_connect("localhost", "hani", "hani") or die(mysql_error());
mysql_select_db("map4") or die(mysql_error());
?>
<?php
$conn = mysql_connect("localhost", "hani", "hani") or die(mysql_error());
mysql_select_db("map4") or die(mysql_error());
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 1300px; height: 600px; border: 0px; padding: 0px; }
</style>
<script src="http://maps.google.com/maps/api/js?key=key=loadMap&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(320, 320), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: 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;
});
}
// random location method start from there
// random location method end there
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
});
<?php
$query = mysql_query("SELECT * FROM map")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$name = $row['name'];
$lat = $row['lat'];
$lon = $row['lon'];
$desc = $row['desc'];
echo("addMarker($lat, $lon, '<b>$name</b><br />$desc');\n");
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
Your code has several syntax problems :
Your function addMarker finishes before the part that generates random markers : you have to move the } after the calls to googlemaps function just before the initMap() function
google.maps.Marker1 : remove the trailing 1
, x0 = long : lng, not long
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
});
OK, Here is my problem. I have a few pages that display points on a map. These points correspond to lat and long in a database of photos that have been uploaded for work that was completed by my employees.
I want to display only the points that correspond to a specific work order. Here is what i have.
This is My Index.php file
<?php include 'active.php';
$work_order = $_REQUEST['work_order'];
global $work_order;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Work Order GPS Data</title>
<style type="text/css">
body { font: normal 14px Verdana; }
h1 { font-size: 24px; }
h2 { font-size: 18px; }
#sidebar { float: right; width: 30%; }
#main { padding-right: 15px; }
.infoWindow { width: 220px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
var map;
var center = new google.maps.LatLng(38.988297, -75.785499);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init() {
var mapOptions = {
zoom: 9,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
makeRequest('get_locations.php?work_order=$work_order', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
function displayLocation(location) {
var content = '<div class="infoWindow"><strong>' + location.name + '</strong>'
+ '<br/>' + location.date_time
+ '<br/>' + location.work_order + '</div>';
if (parseInt(location.lat) == 0) {
geocoder.geocode( { 'address': location.address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: location.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lon));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
}
</script>
</head>
<center>
<body onload="init();">
<h1>Work Order GPS Data</h1>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 95%; height: 840px;"></div>
</section>
</body>
</center>
</html>
Then i have my get_locations.php
<?php
require 'config.php';
$work_order = $_REQUEST['work_order'];
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if($work_order != ''){
$sth = $db->query("SELECT * FROM exif WHERE work_order=$work_order");
}else{$sth = $db->query("SELECT * FROM exif");
}
$locations = $sth->fetchAll();
echo json_encode( $locations );
} catch (Exception $e) {
echo $e->getMessage();
}
My problem is that when i go to http://work.newmansecurity.com/gps/?work_order=1234 i am not only getting points for work order 1234 i am getting all of them. However if i go directly to /gps/get_locations.php?work_order=1234 it works. So some reason the variable is not getting passed as i wish.
Please HELP
Thank you
Try surrounding your variable $work_order in your query with single quotes.
*****SOLVED*****
Changed the
function init() {
var mapOptions = {
zoom: 9,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
makeRequest(<?php echo json_encode($url); ?>, function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
}
To this. Using json encode to pass the variable. Works Great
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
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