PHP and Javascript w/o AJAX situation

Hi, I need some help around the basics of how a small web application would work. I want a user to be able to enter an address, get it geocoded, search a database for predefined locations that are nearby, and return them as markers on a Google Map. The parts I’ve managed to do is the php/mysql part and the final map and markers output. I’ve written a php script that takes geocoordinates from a URI using $_GET, searches the DB for results within a specified distance, and returns the results as markers on a google map. The part I missed when starting is how to feed the geocoordinates, which are provided by google’s API (in javascript) to the php/mysql part. This isn’t normally possible, correct? What I basically want to know is is there a (reasonably simple) way of pulling this off without throwing away my existing PHP?

Sure there is a way.
You just should modify your PHP script to return JSON instead of HTML (or whatever it returns now).

For example (PHP):

$lat = $_GET['lat'];
$lng = $_GET['lng'];
$points_array = getNearestPoints($lat, $lng);
echo json_encode($points_array);
exit;

Sample output:

[{'id': 5, 'title': 'Place 1'}, {'id': 12, 'title': 'Place 2'}]

Then in javascript you can make AJAX-request after receiving coordinates from Google (example uses jQuery):

$.get('script.php', {'lat': latFromGoogle, 'lng': lngFromGoogle}, function(results){

    // here you can iterate through array returned from PHP
    // and add markers on the map:

    for (var i in results){
        var place = results[i];
        addMarker(place.lat, place.lng);
    }

}, 'json');

Thank you for the reply; I should’ve included my code, and I’ll get to processing your reply and seeing how to apply it now.

There is a page that asks the user to input lat, lng and distance, which sends to this page which processes it and produces the map with markers on it; I want the user to enter address instead of lat/lng (don’t know if I should do that on the form page or this processing page or how)

<!doctype html>
<html lang="hr">
<title>Map query test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-old-ie-min.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css">
<!--<![endif]-->
<style type="text/css">
html, body{ height: 100%;}
#map-canvas {
	width:50%;
	height:50%;
	}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA2NRvti7qgHWrOFBzFFoGB_imlEpI-K2A&region=HR"></script>
<script type="text/javascript">
	function initialize() {
		var mapOptions = {
			center: {lat:45.8152919, lng:15.981615},
			zoom: 13
		};
		var map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions
		);
<?php
// Username and password
require("dbcredentials.php");




// Create connection
try {
	$conn = new PDO("mysql:host=localhost;charset=utf8;dbname=$database", $username, $password);
	// set the PDO error mode to exception
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// URL parameters
$lat=$_GET["lat"];
$lng=$_GET["lng"];
$dst=$_GET["dst"];

// Haversine SQL statement
$haversine = "
SELECT  name, address, lat, lng, phone,
			( 6371000 *
				acos(
						COS(RADIANS(?)) *
						COS(RADIANS(?)) * 
						COS(RADIANS(lat)) * 
						COS(RADIANS(lng)) 
						+
						COS(RADIANS(?)) * 
						SIN(RADIANS(?)) * 
						COS(RADIANS(lat)) * 
						SIN(RADIANS(lng)) 
						+ 
						SIN(RADIANS(?)) * 
						SIN(RADIANS(lat))
					)
			) AS distance 
FROM markers
HAVING distance <= ?
ORDER BY distance;
";

// prepare PDO query
$statement = $conn->prepare($haversine);

// bind parameters
$statement->bindValue(1, $lat, PDO::PARAM_STR);
$statement->bindValue(2, $lng, PDO::PARAM_STR);
$statement->bindValue(3, $lat, PDO::PARAM_STR);
$statement->bindValue(4, $lng, PDO::PARAM_STR);
$statement->bindValue(5, $lat, PDO::PARAM_STR);
$statement->bindValue(6, $dst, PDO::PARAM_INT);

// execute query
$statement->execute();

//convert result resource to numeric array
$result = $statement->fetchAll(PDO::FETCH_NUM);

// Maps markers
$numberOfRows = count($result);
$numberOfColumns = 5;
for ($row = 0; $row < $numberOfRows; $row++) {
	$markerLat = $result[$row][2];
	$markerLng = $result[$row][3];
	$markerName = $result[$row][0];
	echo <<<EOT
var markerlatlng$row = new google.maps.LatLng($markerLat,$markerLng);
var marker$row = new google.maps.Marker({
	position: markerlatlng$row,
	map: map,
	title: '$markerName'
	});

EOT;
}


}// End of connection

// Catch errors
catch(PDOException $e)
	{
	echo "Connection failed: " . $e->getMessage();
	}

?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="map-canvas"></div>

Processing that produces

<!doctype html>
<html lang="hr">
<title>Map query test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-old-ie-min.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css">
<!--<![endif]-->
<style type="text/css">
html, body{ height: 100%;}
#map-canvas {
	width:50%;
	height:50%;
	}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA2NRvti7qgHWrOFBzFFoGB_imlEpI-K2A&region=HR"></script>
<script type="text/javascript">
	function initialize() {
		var mapOptions = {
			center: {lat:45.8152919, lng:15.981615},
			zoom: 13
		};
		var map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions
		);
var markerlatlng0 = new google.maps.LatLng(45.810528,15.975953);
var marker0 = new google.maps.Marker({
	position: markerlatlng0,
	map: map,
	title: 'Kolding'
	});
var markerlatlng1 = new google.maps.LatLng(45.810783,15.972994);
var marker1 = new google.maps.Marker({
	position: markerlatlng1,
	map: map,
	title: 'Fax-Copy'
	});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="map-canvas"></div>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.