Online Store Locator Using PHP, MySQL and Google Maps API
Online Store Locator Using PHP, MySQL and Google Maps API
Posted on February 3, 2013 by theoryapp Where is the closest McDonalds? This tutorial shows how to build a map-based locator for finding the closest stores. We will use PHP and MySQL for the backend and JavaScript with Google Maps API for the front end.
1 SELECT *, 2 ( 3959 * acos( cos(radians(lat0)) * cos(radians(lat)) * 3 cos(radians(lng) - radians(lng0)) + sin(radians(lat0)) * sin(radians(lat)) ) ) AS distance 4 FROM `data_mcdonalds` 5 HAVING distance < 50 6ORDER BY distance LIMIT 20; 7
"distance" => $row['distance'] 39 )); 40 } 41 42$ret = array( 43 "status" => "OK", "data" => $result_array); 44 die(json_encode($ret)); 45 46?> 47 48 49 50 51 52 53 54
20function searchAddress(address) { geocoder.geocode( { 'address': address}, 21 function(results, status) { 22 if (status === google.maps.GeocoderStatus.OK) { 23 var latlng = results[0].geometry.location; map.setCenter(latlng); 24 searchStores(latlng.lat(), latlng.lng()); 25 } else { 26 alert('Address not found: ' + status); 27 } 28 }); 29} 30 31function searchStores(lat, lng) { var url = './store-ajax.php'; 32 var parameter = { lat: lat, lng: lng }; 33 jQuery.ajax({ url: url, 34 data: parameter, 35 dataType: 'json', 36 success: showStores 37 }); 38} 39 40function showStores(data, status, xhr) { if (data['status'] != 'OK') 41 return; 42 43 infoWindow.close(); 44 for (var i = 0; i < markers.length; i++) { 45 markers[i].setMap(null); } 46 markers.length = 0; 47 48 for (var i in data['data']) { 49 createMarker(data['data'][i]); 50 } 51} 52 53function createMarker(store) { var latlng = new google.maps.LatLng( 54 parseFloat(store['lat']), 55 parseFloat(store['lng']) 56 ); var html = "<b>" + store['address'] + "</b>" + 57 store['distance'] + " miles"; 58 var marker = new google.maps.Marker({ 59 map: map, 60 position: latlng }); 61 google.maps.event.addListener(marker, 'click', function() { 62 infoWindow.setContent(html); 63 infoWindow.open(map, marker); 64 }); 65 markers.push(marker); } 66