如何从api.php数据库获取经纬度并在Mapbox上展示多边形?
Got it, let's break this down step by step to get your database coordinates showing up as a polygon in Mapbox. Here's how to make it work:
Step 1: Update your api.php to return valid GeoJSON
First, we need api.php to connect to your database, pull the latitude/longitude points, and format them into the GeoJSON structure Mapbox expects. Mapbox uses longitude first, latitude second for coordinates, so make sure you swap them if your database stores lat/lon in the reverse order.
Here's a sample api.php using PDO (adjust the database credentials and query to match your setup):
<?php // Allow cross-origin requests if your frontend is on a different domain header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json"); // Database connection details - replace with your own $dbHost = 'localhost'; $dbName = 'your_database_name'; $dbUser = 'your_db_username'; $dbPass = 'your_db_password'; try { // Connect to the database $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Query your polygon points - adjust the table/column names to match your schema // This example assumes you have a table `polygon_points` with columns: polygon_id, lon, lat, point_order // We're fetching points for a single polygon (id=1) and ordering them correctly $stmt = $pdo->prepare("SELECT lon, lat FROM polygon_points WHERE polygon_id = 1 ORDER BY point_order ASC"); $stmt->execute(); $points = $stmt->fetchAll(PDO::FETCH_ASSOC); // Format points into [lon, lat] pairs, and close the polygon (last point = first point) $coordinates = []; foreach ($points as $point) { $coordinates[] = [(float)$point['lon'], (float)$point['lat']]; } // Close the polygon to ensure Mapbox renders it correctly if (!empty($coordinates)) { $coordinates[] = $coordinates[0]; } // Assemble the final GeoJSON Feature $geoJson = [ 'type' => 'Feature', 'geometry' => [ 'type' => 'Polygon', 'coordinates' => [$coordinates] // Polygons require an array of rings (we have one ring here) ] ]; // Output the JSON echo json_encode($geoJson); } catch (PDOException $e) { // Handle database errors http_response_code(500); echo json_encode(['error' => 'Failed to fetch data: ' . $e->getMessage()]); } ?>
Step 2: Modify your Mapbox frontend code to fetch the data
Instead of hardcoding the coordinates array, we'll use the Fetch API to pull the GeoJSON from api.php, then pass it to Mapbox's source.
Here's the updated frontend code:
map.on('load', function() { // Fetch GeoJSON data from your API fetch('api.php') .then(response => { if (!response.ok) { throw new Error('Failed to load polygon data'); } return response.json(); }) .then(geoJsonData => { // Add the source with the fetched data map.addSource('maine', { 'type': 'geojson', 'data': geoJsonData }); // Add the fill layer as before map.addLayer({ 'id': 'maine', 'type': 'fill', 'source': 'maine', 'layout': {}, 'paint': { 'fill-color': '#088', 'fill-opacity': 0.8 } }); }) .catch(error => { console.error('Error loading polygon:', error); }); });
Key Notes to Keep in Mind
- Coordinate Order: Double-check that you're passing
[lon, lat]to Mapbox. If your database storeslatfirst, swap them in theapi.phploop. - Polygon Closure: Always close your polygon by repeating the first point as the last point—this ensures Mapbox renders it as a solid shape.
- Multiple Polygons: If you need to show multiple polygons, modify
api.phpto return aFeatureCollection(an array of Features) instead of a single Feature. Your frontend code will work without changes, as Mapbox handles FeatureCollections natively. - Database Schema: Adjust the SQL query to match your actual table structure. For example, if you store polygon coordinates as a JSON array in a single column, you can skip the loop and directly decode that JSON.
内容的提问来源于stack exchange,提问作者Thulaksan Jayapal

