Home > Backend Development > PHP Tutorial > Use php to develop Websocket to implement real-time map positioning function

Use php to develop Websocket to implement real-time map positioning function

WBOY
Release: 2023-12-17 20:10:01
Original
1287 people have browsed it

Use php to develop Websocket to implement real-time map positioning function

Title: Using PHP to develop Websocket to implement real-time map positioning function

Introduction:
Websocket is a protocol that implements persistent connections and real-time two-way communication, which can achieve Real-time data transfer and updates. This article will use PHP to develop Websocket, combined with the map positioning function, to achieve real-time map positioning function. The specific code implementation process will be introduced in detail below.

1. Preparation

  1. Install PHP environment (version requirement: PHP 5.3.0)
  2. Install Composer (PHP third-party library management tool)

2. Install related libraries

  1. Open the command line, enter the directory where the project is located, and execute the following command to install the Ratchet library:

    composer require cboden/ratchet
    Copy after login
  2. Install Once completed, copy the generated vendor directory to the project root directory.

3. Implement WebSocket server

  1. Create a server.php file and add the following code:

    <?php
    require 'vendor/autoload.php';
    
    use RatchetMessageComponentInterface;
    use RatchetConnectionInterface;
    use RatchetServerIoServer;
    use RatchetHttpHttpServer;
    use RatchetWebSocketWsServer;
    
    class MapLocation implements MessageComponentInterface 
    {
     protected $clients;
    
     public function __construct() {
         $this->clients = new SplObjectStorage;
     }
    
     public function onOpen(ConnectionInterface $conn) {
         $this->clients->attach($conn);
         echo "New connection! ({$conn->resourceId})
    ";
     }
    
     public function onClose(ConnectionInterface $conn) {
         $this->clients->detach($conn);
         echo "Connection closed! ({$conn->resourceId})
    ";
     }
    
     public function onMessage(ConnectionInterface $from, $msg) {
         foreach ($this->clients as $client) {
             $client->send($msg);
         }
     }
    
     public function onError(ConnectionInterface $conn, Exception $e)
     {
         echo "An error occurred: {$e->getMessage()}
    ";
         $conn->close();
     }
    }
    
    $server = IoServer::factory(
     new HttpServer(
         new WsServer(
             new MapLocation()
         )
     ),
     8080
    );
    
    $server->run();
    Copy after login

4. Implement the front-end page

  1. Create an index.html file and add the following code:

    <!DOCTYPE html>
    <html>
    <head>
     <meta charset="UTF-8">
     <title>实时地图定位</title>
     <style>
         #map {
             width: 800px;
             height: 600px;
             border: 1px solid #ccc;
         }
     </style>
     <script src="https://cdn.leafletjs.com/leaflet/v1.3.1/leaflet.js"></script>
     <link rel="stylesheet" href="https://cdn.leafletjs.com/leaflet/v1.3.1/leaflet.css" />
    </head>
    <body>
     <div id="map"></div>
    
     <script>
         var map = L.map('map').setView([39.9075, 116.39723], 13);
         L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
             maxZoom: 18,
             attribution: 'Map data &copy; OpenStreetMap contributors'
         }).addTo(map);
    
         var ws = new WebSocket("ws://localhost:8080");
    
         ws.onmessage = function (event) {
             var data = JSON.parse(event.data);
             var marker;
    
             if (data.action === 'add') {
                 marker = L.marker([data.lat, data.lng]).addTo(map);
             } else if (data.action === 'update') {
                 marker = markers[data.id];
                 if (marker) {
                     marker.setLatLng([data.lat, data.lng]);
                 }
             } else if (data.action === 'remove') {
                 marker = markers[data.id];
                 if (marker) {
                     map.removeLayer(marker);
                 }
             }
    
             if (marker) {
                 markers[data.id] = marker;
             }
         };
    
         var markers = {};
     </script>
    </body>
    </html>
    Copy after login

5. Test and run

  1. Open the terminal, enter the directory where the project is located, and execute the following command:

    php server.php
    Copy after login
  2. Open the index.html file in the browser, and you will see a map interface.
  3. You can simulate different data updates by modifying the sending data in the onMessage method in server.php.

Summary:
This article introduces how to use PHP to develop Websocket and combine it with the map positioning function to achieve real-time map positioning function. By writing code for server-side and front-end pages, we can update marker location information on the map in real time via Websocket. In actual projects, more functions and data interactions can be added according to needs.

The above is the detailed content of Use php to develop Websocket to implement real-time map positioning function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template