How to Display Nearby Points of Interest Using PHP and Baidu Maps API
This tutorial explains step-by-step how to register a Baidu Maps developer account, set up a PHP script, create an HTML page with a map container, retrieve geographic coordinates via JavaScript, call the Baidu Maps API to fetch nearby points of interest, and render them on the page.
In the current internet era, map navigation is essential, and displaying nearby points of interest (POI) in a project is a common requirement.
Step 1: Register a Baidu developer account and create an application – Sign up on the Baidu Maps Open Platform, create an app, and obtain an API Key for later use.
Step 2: Create a PHP file and include the Baidu Maps API
The require_once statement loads the main BaiduMapAPI.php library, which provides the necessary functions and interfaces.
Step 3: Build the front‑end page and map container
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>项目周边兴趣点展示</title>
<style type="text/css">
/* Map container style */
#map-container{
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<div id="map-container"></div>
</body>
</html>This HTML creates a simple page with a div whose id map-container will hold the map and POI information.
Step 4: Write backend code to obtain and display POI
setCenter($longitude, $latitude);
// Get nearby POI list
$poi_list = $map->getPOIList($longitude, $latitude);
// Output POI information
foreach ($poi_list as $poi) {
echo $poi['name'] . ' - ' . $poi['address'] . "
";
}
?>The script retrieves the coordinates sent from the front end, creates a BaiduMapAPI object, sets the center point, calls getPOIList to fetch POIs, and echoes each POI’s name and address.
Step 5: Use Ajax to acquire the user’s location and call the backend
// Get user location
navigator.geolocation.getCurrentPosition(function(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
// Send Ajax request
var xhr = new XMLHttpRequest();
xhr.open("GET", "poi.php?longitude=" + longitude + "&latitude=" + latitude, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Display POI information in the map container
document.getElementById("map-container").innerHTML = xhr.responseText;
}
};
xhr.send();
});This JavaScript obtains the user’s geographic coordinates, sends them to poi.php via an XMLHttpRequest, and inserts the returned POI list into the map-container element.
Following these steps, you can integrate PHP with the Baidu Maps API to show nearby points of interest, providing users with enhanced navigation and location experiences.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.