I am doing this first time, how can I add google map in my website? I have done AJAX please see this code and give me answer
The area that comes throw database using AJAX, Area are perfectly done and "latitude" & "longitude" are perfectly got it, but I can't use that latitude & longitude in JavaScript code.
this is my php file code is:
<div class="col-lg-4">
<select name="area_id" class="form-control" onchange="showUser(this.value)" id="area">
<option value="">Select Area</option>
</select>
</div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</div>
<div id="txtHint"><b>Person info will be listed here...</b></div>
this is getuser.php file:
<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=" My Map Key "&callback=initMap"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style>
#txtHint {
height: 350px;
}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
echo $sql = "SELECT * FROM area WHERE area_id='$q'";
$qry = mysql_query($sql);
while($fetch = mysql_fetch_array($qry))
{
$area_name=$fetch['area_name'];
//$city_name=$fetch['city_name'];
$address =$area_name; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$area_latitude = $output->results[0]->geometry->location->lat;
$area_longitude = $output->results[0]->geometry->location->lng;
echo "<br><input type='text' name='area_latitude' id='area_latitude'value='".$area_latitude."'> <br>";
echo "<input type='text' name='area_longitude' id='area_longitude' value='".$area_longitude."'>";
?>
<script type="text/javascript">
var map;
var marker;
var area_latitude = $("#area_latitude").val();
var area_longitude = $("#area_longitude").val();
var myLatlng = new google.maps.LatLng(area_latitude, area_longitude);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("txtHint"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({
'latLng': myLatlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({
'latLng': marker.getPosition()
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<?php }
?>
</body>
</html>
The values being returned by this are probably strings ("1.2345") instead of Floats (1.2345), which is what the Google Maps expects for coordinates:
var area_latitude = $("#area_latitude").val();
var area_longitude = $("#area_longitude").val();
Try:
var area_latitude = parseFloat($("#area_latitude").val());
var area_longitude = parseFloat($("#area_longitude").val());
Related
I have a script(get_search_data.php) that performs search from the database based on the keyword fname. i wish that according to the search result, locations should get displayed on the map (display_map.php) along with the marker and popup window for information.
table view for features_for_office
id fname co_address_line1 co_address_line2 lat lon
get_search_data.php
<?php
require 'config.php';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$fname = $_POST['fname'];
$sth = "SELECT * FROM features_for_office WHERE fname LIKE :fname ";
$stmt = $db->prepare($sth);
$stmt->bindValue(':fname', '%' . $fname . '%', PDO::PARAM_STR);
$stmt->execute();
$locations = $stmt->fetchAll();
echo json_encode( $locations );
} catch (Exception $e) {
echo $e->getMessage();
}
?>
<script src="jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
$('#drop2').on('change',function(){
//var fname = $(this).val();
var fname = $(this).find('option:selected').text();
// rename your file which include $fname with get_search_data.php
if(fname !== ""){
$.post('display_map.php',{fname: fname},function(data){
$('.showsearch').html(data);
});
}
});
});
</script>
display_map.php
<style type="text/css">
#main { padding-right: 15px; }
.infoWindow { width: 220px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
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;
// Ban Jelačić Square - City Center
var center = new google.maps.LatLng(21.0000, 78.0000);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function init()
{
var mapOptions =
{
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
makeRequest('get_search_data.php', 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.fname + '</strong>'
+ '<br/>' + location.co_address_line1
+ '<br/>' + location.co_address_line2 + '</div>';
if (parseInt(location.lat) == 0)
{
geocoder.geocode( { 'address': location.co_address_line1 }, 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>
<body onload="init();">
<section id="main">
<div id="map_canvas" style="width: 70%; height: 500px;"></div>
</section>
</body>
Although the map gets displayed but the markers are not getting displayed. would appreciate any help
It might be strange answer, but your code should work.
But if you mix up lat and lon in your database markers would still display but you won't see them because they appear in another part of the world.
If I am wrong please post the the structure of json response from php script
I have two mysql tables: "cars" and "locations".
Cars are assigned to a locations by having field "location_id" in "cars" table. I am showing locations in a google maps retrieving coordinates from "locations" table.
What I would like to do, is to show in info window of google maps marker (which mark a location) which cars are assigned to this location.
I use get_locations.php with this code to retrieve information from DB:
$query_cars = "SELECT * FROM cars where location_lat not like ''";
$cars = $db->query($query_cars);
$row_cars = $cars->fetchAll(PDO::FETCH_ASSOC);
$query_locations = "SELECT id, name, gpslat, gpslong FROM locations where name not like '%/ Zona%' and status='Activa'";
$locations = $db->query($query_locations);
$rowLocations = $locations->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rowLocations);
Than I call this script from html page with this code:
<!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=API KEY">
</script>
<script type="text/javascript">
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 geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.430013, -3.695854),
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
makeRequest('get_locations.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
var image = 'http://www.bluemove.es/equipo/images/car_location_Normal.png';
function displayLocation(location) {
var content = '<div class="infoWindow">' + location.name; // content of the pop up window
if (parseInt(location.gpslat) == 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,
incon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(location.gpslat), parseFloat(location.gpslong));
var marker = new google.maps.Marker({
map: map,
position: position,
title: location.name,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map,marker);
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
So when marker is clicked, the location name is displayed on the info window. But as I said I also want to display car name that are assigned to this location.
Does anybody have any idea?
Thank you!
You have to make an INNER JOIN query so the $rowLocations will contain both table values.
Something like that:
SELECT * FROM cars AS c INNER JOIN locations AS l ON c.cars = l.location_id
WHERE c.location_lat NOT LIKE "'" AND l.name NOT LIKE '%/ Zona%';
I'm quite new to Google Maps API but while doing some research the other day I saw this.
https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple
Is it as easy as putting php into that contentString
<?php
$query = mysql_query("SELECT products_zipcode FROM products ")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$zip = $row['products_zipcode'];
}
?>
here how to assign $zip variable value to java script variable var address = zip;
<script type="text/javascript">
function codeAddress(zip) {
var address = zip;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
</script >
Here changed the code
as
per the answers
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("coachup_db1") or die(mysql_error());
?>
<?php
$query = mysql_query("SELECT products_zipcode FROM products ")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
$zip[] = $row['products_zipcode'];
// echo("codeAddress($zip)");
}
?>
<div id="map-canvas"></div>
<style>
#map-canvas {
width: 300px;
height: 200px;
margin: 0px;
padding: 0px;
border: 0px; padding: 0px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 4,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = <?php echo json_encode($zip); ?>;
var overallcontent = <?php echo json_encode($zip); ?>;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', codeAddress);
</script>
you can assign a php variable to a javascript variable using the following method.
var address =<?php echo json_encode($zip) ?>;
on the other hand if you want to assign a php array to a javascript variable than:
var overallcontent = <?php echo json_encode($type); ?>;
where $type is a php array.
var address = "<?php echo $zip ?>";
Simply echo it and store it in a JavaScript variable. Here's how:
var address = "<?php echo $zipCode' ?>";
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've set up google map API that loads data from mysql database and display markers. the problem I am facing is that all the markers shows up at once no matter whatever I input in search location field.............. I want to show only the searched area and markers in that area. It shouldn't display all the markers at once but only the marker in the searched area.
I mean I want to zoom the map to the searched area. Currently if I've only one marker map zoom in to show that but if I've many markers the map zoom out to show all the markers. Here is the map I'm working on "http://funfeat.com/clients/gmap/gmap3.html" NOW I've set markers very very far and the map is still showing all the markers by zooming out.
The gmap.php is the file that provide xml results from mysql database. and the below code is what I am using to display map
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 10,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
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 = 'gmap.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 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 + "(" + distance.toFixed(1) + ")";
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>
</head>
<body style="margin:0px; padding:0px;" onLoad="load()">
<div>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="25" selected>25mi</option>
<option value="100">100mi</option>
<option value="200">200mi</option>
</select>
<input type="button" onClick="searchLocations()" value="Search"/>
</div>
<div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
<div id="map" style="width: 100%; height: 80%"></div>
</body>
</html>
http://funfeat.com/clients/gmap/gmap.php?lat=47&lng=-122&radius=2 produces valid XML but your query must be wrong .It pulls out 10 markers, 9 of which are correct but the 10th produces <marker name="Pakistan" address="Chowk Azam, Layyah" lat="31.008364" lng="71.224342" type="cITY"/> which is certainly not within 2 miles of the coordinates. Your query should not pick up the last marker from the database.
As the use of mysql_ functions are discouraged the following code uses PDO can be used
//dependant on your setup
$host= "WWW";
$username="XXX";
$password="YYY";
$database="ZZZ";
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Prepare statement
$stmt = $dbh->prepare("SELECT name, lat, lng, ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM gbstn HAVING distance < ? ORDER BY distance ASC LIMIT 0 , 20");
// Assign parameters
$stmt->bindParam(1,$center_lat);
$stmt->bindParam(2,$center_lng);
$stmt->bindParam(3,$center_lat);
$stmt->bindParam(4,$radius);
//Execute query
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
EDIT Added to catch error if no records found
if ($stmt->rowCount()==0) {
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", "No Records Found");
$newnode->setAttribute("lat", $center_lat);//Sends marker to search location
$newnode->setAttribute("lng", $center_lng);
$newnode->setAttribute("distance", 0);
}
else {
End of EDIT
// Iterate through the rows, adding XML nodes for each
while($row = $stmt->fetch()) {
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
}
echo $dom->saveXML();
}
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", gmap.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$dbh = null;
The part of the query above HAVING distance < '%s' is the part that should weed out the last marker.
I have added Error catch if no records are found in search and Map sent to lat/lng 0,0. See My Implementation Here