Current Location: Home> Latest Articles> PHP Tutorial: Implement Marker Click Event Response Using Baidu Map API

PHP Tutorial: Implement Marker Click Event Response Using Baidu Map API

M66 2025-07-31

Include Baidu Map API JavaScript Library

Baidu Map API offers powerful map functions and interactive capabilities for websites and mobile applications. To use Baidu Map in a PHP project, you first need to include the Baidu Map JavaScript library in your page. Here is an example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=YOUR_BAIDU_MAP_API_KEY"></script>
  </head>
  <body>
    <div id="map" style="width: 100%; height: 400px;"></div>
  </body>
</html>

Please replace YOUR_BAIDU_MAP_API_KEY with the valid key you obtained from Baidu Map Developer Platform. The

tag serves as the container to display the map.

Create Map Instance Using PHP

After successfully including the API library, you can use PHP to output JavaScript code dynamically to create a map instance, set the center point, and zoom level:

<?php
 echo '<script type="text/javascript">
     var map = new BMap.Map("map");  // Create map instance
     var point = new BMap.Point(116.404, 39.915);  // Set center coordinates
     map.centerAndZoom(point, 15);  // Initialize map with center point and zoom level
 </script>';
?>

In this code, the map will be displayed inside the container with ID map, and the center coordinates correspond to Beijing.

Add Marker and Bind Click Event

To respond to marker clicks, create a marker object and attach a click event listener:

<?php
 echo '<script type="text/javascript">
     // Create marker
     var marker = new BMap.Marker(point);
     map.addOverlay(marker);

     // Add click event listener
     marker.addEventListener("click", function(){
       alert("You clicked the marker!");
     });
 </script>';
?>

This code adds the marker to the map and shows an alert when it is clicked. You can customize the event handler to show info windows, open links, or perform other actions as needed.

Summary

Following the steps above, you can easily integrate Baidu Map API in your PHP project to implement interactive marker click events. Baidu Map API offers many advanced features; it is recommended to explore the official documentation to enhance your map applications further.