Question

I'm using Routerboxer to generate a list of latitudes and longitudes within a certain route. I want to send the lat and lngs back to my database query (I presume using ajax) to return markers within the bounds.

I have searched and found the database query needs to be:

SELECT * FROM as24 WHERE lat > a AND lat < c AND lng > b AND lng < d

My question is how do I send these a,b,c and d's to the PHP page?

function calcRoute() {
clearBoxes();
distance = 10 * 1.609344; //within 10 miles
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(result);

      // Box around the overview path of the first route
      var path = result.routes[0].overview_path;
      var boxes = routeBoxer.box(path, distance);
      drawBoxes(boxes);
    } else {
      alert("Directions query failed: " + status);
    }
  });
}



// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
  boxpolys = new Array(boxes.length);
  for (var i = 0; i < boxes.length; i++) {
    boxpolys[i] = new google.maps.Rectangle({
      bounds: boxes[i],
      fillOpacity: 0,
      strokeOpacity: 1.0,
      strokeColor: '#000000',
      strokeWeight: 1,
      map: map
      //Perform Search
    });
  }
}

// Clear boxes currently on the map
function clearBoxes() {
  if (boxpolys != null) {
    for (var i = 0; i < boxpolys.length; i++) {
      boxpolys[i].setMap(null);
    }
  }
  boxpolys = null;
}


google.maps.event.addDomListener(window, "load", initialize);

function load() {

var infoWindow = new google.maps.InfoWindow;

// Change this depending on the name of your PHP file
downloadUrl("as24_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
  var name = markers[i].getAttribute("name");
  var address = markers[i].getAttribute("address");
  var price = markers[i].getAttribute("price");
  var type = markers[i].getAttribute("type");
  var point = new google.maps.LatLng(
      parseFloat(markers[i].getAttribute("lat")),
      parseFloat(markers[i].getAttribute("lng")));
  var html = "<b>" + name + " " + price + "</b> <br/>" + address;
  var icon = customIcons[type] || {}; 
  var marker = new google.maps.Marker({
    map: map,
    position: point,
    icon: icon.icon
  });
  map.getBounds().contains(marker.getPosition())
  bindInfoWindow(marker, map, infoWindow, html);
  $.post("as24_genxml.php",
{
  a:map.getBounds().getNorthEast().lat(),
  b:map.getBounds().getNorthEast().lng(),
  c:map.getBounds().getSouthWest().lat(),
  d:map.getBounds().getSouthWest().lng()
},
 function(data,status){

});


}
});
}

As you can see I've tried to do this via an ajax php send.

My php file looks like this:

<?php include ('php/config.php');

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
return $xmlStr; 
} 

// Opens a connection to a MySQL server
$connection=mysql_connect ($mysql_server, $mysql_user, $mysql_pass);
if (!$connection) {
die('Not connected : ' . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($mysql_db, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the markers table
$query = "SELECT * FROM as24 WHERE lat > a AND lat < c AND lng > b AND lng < d";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'price="' . parseToXML($row['price']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}

// End XML file
echo '</markers>';

?>
Was it helpful?

Solution

Here is an example of how to send the bounds to your PHP code using jQuery.ajax().

var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();

$.ajax({

    url: 'your_file.php',
    cache: false,
    data: {
        'fromlat': southWest.lat(),
        'tolat': northEast.lat(),
        'fromlng': southWest.lng(),
        'tolng': northEast.lng()
    },
    dataType: 'json',
    async: false,
    success : function(data) {

        $.each(data, function(i,marker) {

            createMarker(marker);
        });
    }
});

function createMarker(data) {

     // Check what you have here in "data" and construct your markers from here as you would do for any marker.
}

In your PHP:

$fromlat = $_GET['fromlat'];
$tolat = $_GET['tolat'];
$fromlng = $_GET['fromlng'];
$tolng = $_GET['tolng'];

$results = array();

$sql = "SELECT * from your_table where (lat>'" . $db->real_escape_string($fromlat) . "' and lat<'" . $db->real_escape_string($tolat) . "' and lng>'" . $db->real_escape_string($fromlng) . "' and lng<'" . $db->real_escape_string($tolng) . "')";

$result = $db->query($sql) or die($db->error);

while ($obj = $result->fetch_object()) {

    $results[] = $obj;
}

echo json_encode($results);

Of course if you like POST instead of GET, you can adapt.

OTHER TIPS

I would suggest using a web service to achieve this, passing the long lats and returning as needed. A simple example is available here: http://davidwalsh.name/web-service-php-mysql-xml-json, http://www.php.net/manual/en/refs.webservice.php and more at: php web service example

This will allow you to use the service from any location should you need to in the future (extensibility is always nice).

You can access the service using jQuery ajax calling the method to update the map on the return of the results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top