You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Google Map可编辑多边形编辑后坐标获取及后端提交问题

Hey there! Let's figure out how to capture those edited polygon coordinates and send them off to your backend. I'll walk you through the solution step by step, using code examples based on the popular @react-google-maps/api library (since that's the most common React wrapper for Google Maps these days).

Step 1: Set Up References and Edit Event Listeners

First, you'll need a way to access the Google Maps Polygon instance directly, and listen for when the polygon gets edited. We'll use React's useRef to hold the polygon reference, and leverage the polygon's onChange event to trigger our coordinate capture logic.

Step 2: Extract and Format Coordinates

Once the polygon is edited, we'll pull the updated path from the polygon instance, convert the raw Google Maps LatLng objects into a plain JavaScript array (easy for your backend to parse), and then send that data via an API call.

Full Code Example

import { GoogleMap, Polygon, useLoadScript } from '@react-google-maps/api';
import { useRef, useState } from 'react';
import axios from 'axios'; // Or use native fetch if you prefer

const MapWithEditablePolygon = () => {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY',
  });

  // State to hold initial/updated polygon coordinates (from your backend)
  const [polygonCoords, setPolygonCoords] = useState([
    // Replace with your backend-provided initial coordinates
    { lat: 40.712776, lng: -74.005974 },
    { lat: 40.735657, lng: -74.008572 },
    { lat: 40.728178, lng: -73.999902 },
  ]);

  // Ref to access the Google Maps Polygon instance
  const polygonRef = useRef(null);

  // Handle polygon edits and submit updated coordinates
  const handlePolygonEdit = () => {
    if (!polygonRef.current) return;

    // Get the updated path from the polygon
    const updatedPath = polygonRef.current.getPath();
    
    // Convert Google Maps LatLng objects to a plain array of {lat, lng} objects
    const formattedCoords = Array.from(updatedPath).map(latLng => ({
      lat: latLng.lat(),
      lng: latLng.lng(),
    }));

    // Update local state to sync UI with edited coordinates
    setPolygonCoords(formattedCoords);

    // Send the coordinates to your backend
    submitToBackend(formattedCoords);
  };

  // API call to submit coordinates
  const submitToBackend = async (coords) => {
    try {
      const response = await axios.post('/api/update-polygon', {
        polygonCoordinates: coords,
      });
      console.log('Coordinates submitted successfully:', response.data);
      // Add success feedback here (e.g., toast notification)
    } catch (error) {
      console.error('Failed to submit coordinates:', error);
      // Add error handling here (e.g., error message to user)
    }
  };

  if (!isLoaded) return <div>Loading map...</div>;

  return (
    <GoogleMap
      mapContainerStyle={{ width: '100%', height: '600px' }}
      center={{ lat: 40.712776, lng: -74.005974 }}
      zoom={13}
    >
      <Polygon
        ref={polygonRef}
        paths={polygonCoords}
        editable={true} // Enables vertex editing
        draggable={true} // Optional: allows dragging the entire polygon
        onChange={handlePolygonEdit} // Triggers on any edit action
        options={{
          fillColor: '#2196F3',
          fillOpacity: 0.3,
          strokeColor: '#2196F3',
          strokeOpacity: 1,
          strokeWeight: 2,
        }}
      />
    </GoogleMap>
  );
};

export default MapWithEditablePolygon;

Key Details to Note

  • Polygon Reference: The polygonRef gives us direct access to the underlying Google Maps Polygon instance, which lets us call getPath() to get the updated vertex coordinates.
  • onChange Event: This event fires whenever any edit happens (dragging a vertex, adding a vertex, deleting a vertex) — perfect for capturing the latest state of the polygon.
  • Coordinate Formatting: Converting LatLng objects to plain {lat, lng} objects ensures your backend can easily parse and store the data.
  • Backend Submission: Use axios (or native fetch) to send a POST request to your backend endpoint with the formatted coordinates. Adjust the endpoint URL and request body structure to match your backend's requirements.

If You're Using a Different Google Maps Library

If you're using an older library like react-google-maps, the core logic stays the same:

  1. Get a reference to the Polygon component
  2. Listen for edit-related events (like onMouseUp or onPolygonChanged)
  3. Extract the path and format it for your backend

内容的提问来源于stack exchange,提问作者Sankar Martha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:55:20