最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to get show the boundry of a place with Google Maps? - Stack Overflow

programmeradmin2浏览0评论

Similar to Google Map itself i wanna highlight my place with its boundry (like red dotted line google does)

I have tried CHATGPT but got no response and also the google docs have nothing usefull for this

This is what i have tried yet

"use client";

import { useState, useRef } from "react";
import { GoogleMap, LoadScript, Polygon, Autocomplete } from "@react-google-maps/api";

const API_KEY = "YOUR_GOOGLE_MAPS_API_KEY"; // Replace with your actual API key

const libraries: any = ["places"]; // Enables Google Places API

const containerStyle = { width: "100%", height: "500px" };
const defaultCenter = { lat: 24.8607, lng: 67.0011 }; // Default: Karachi

export default function GoogleMapComponent() {
  const [map, setMap] = useState<google.maps.Map | null>(null);
  const [placeDetails, setPlaceDetails] = useState<any>(null);
  const [polygonCoords, setPolygonCoords] = useState<google.maps.LatLngLiteral[]>([]);
  const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);

  // Function to fetch and display place boundary
  const onPlaceSelected = async () => {
    if (!autocompleteRef.current) return;

    const place = autocompleteRef.current.getPlace();
    if (!place.geometry || !place.place_id) return;

    setPlaceDetails({
      name: place.name,
      address: place.formatted_address,
      placeId: place.place_id,
    });

    // Fetch place boundary from Google Maps internal data
    fetchPlaceBoundary(place.place_id);

    // Center the map
    map?.panTo(place.geometry.location!);
  };

  // Fetching place boundary using the Place ID
  const fetchPlaceBoundary = async (placeId: string) => {
    try {
      const service = new google.maps.places.PlacesService(map!);

      service.getDetails({ placeId }, (place, status) => {
        if (status === google.maps.places.PlacesServiceStatus.OK && place.geometry) {
          const bounds = new google.maps.LatLngBounds();
          if (place.geometry.viewport) {
            place.geometry.viewport.extend(bounds.getNorthEast());
            place.geometry.viewport.extend(bounds.getSouthWest());
          }

          // Attempt to get more detailed boundaries
          if (place.address_components) {
            setPolygonCoords(generateMockBoundary(place.geometry.location!)); // Generate mock boundaries
          }
        }
      });
    } catch (error) {
      console.error("Error fetching boundary:", error);
    }
  };

  // Function to generate a sample boundary (replace with real API if needed)
  const generateMockBoundary = (center: google.maps.LatLng) => {
    const lat = center.lat();
    const lng = center.lng();

    return [
      { lat: lat + 0.01, lng: lng - 0.01 },
      { lat: lat + 0.01, lng: lng + 0.01 },
      { lat: lat - 0.01, lng: lng + 0.01 },
      { lat: lat - 0.01, lng: lng - 0.01 },
    ];
  };

  return (
    <LoadScript googleMapsApiKey={API_KEY} libraries={libraries}>
      <div className="p-4">
        {/* Search Box */}
        <Autocomplete
          onLoad={(autocomplete) => (autocompleteRef.current = autocomplete)}
          onPlaceChanged={onPlaceSelected}
        >
          <input
            type="text"
            placeholder="Search for an area..."
            className="w-full p-2 border border-gray-300 rounded"
          />
        </Autocomplete>

        {/* Display Selected Place Details */}
        {placeDetails && (
          <div className="mt-4 p-3 bg-gray-100 rounded">
            <h3 className="text-lg font-semibold">{placeDetails.name}</h3>
            <p>{placeDetails.address}</p>
            <p><strong>Place ID:</strong> {placeDetails.placeId}</p>
          </div>
        )}

        {/* Map Display */}
        <div className="mt-4">
          <GoogleMap mapContainerStyle={containerStyle} center={defaultCenter} zoom={13} onLoad={setMap}>
            {/* Draw Polygon with Dashed Border */}
            {polygonCoords.length > 0 && (
              <Polygon
                paths={polygonCoords}
                options={{
                  strokeColor: "#FF0000",
                  strokeOpacity: 1,
                  strokeWeight: 2,
                  fillColor: "transparent",
                  fillOpacity: 0,
                  strokeDashArray: [5, 5], // Makes it a dashed line like Google Maps
                }}
              />
            )}
          </GoogleMap>
        </div>
      </div>
    </LoadScript>
  );
}

it would be a great help if someone can tell me how to implement this?

Similar to Google Map itself i wanna highlight my place with its boundry (like red dotted line google does)

I have tried CHATGPT but got no response and also the google docs have nothing usefull for this

This is what i have tried yet

"use client";

import { useState, useRef } from "react";
import { GoogleMap, LoadScript, Polygon, Autocomplete } from "@react-google-maps/api";

const API_KEY = "YOUR_GOOGLE_MAPS_API_KEY"; // Replace with your actual API key

const libraries: any = ["places"]; // Enables Google Places API

const containerStyle = { width: "100%", height: "500px" };
const defaultCenter = { lat: 24.8607, lng: 67.0011 }; // Default: Karachi

export default function GoogleMapComponent() {
  const [map, setMap] = useState<google.maps.Map | null>(null);
  const [placeDetails, setPlaceDetails] = useState<any>(null);
  const [polygonCoords, setPolygonCoords] = useState<google.maps.LatLngLiteral[]>([]);
  const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);

  // Function to fetch and display place boundary
  const onPlaceSelected = async () => {
    if (!autocompleteRef.current) return;

    const place = autocompleteRef.current.getPlace();
    if (!place.geometry || !place.place_id) return;

    setPlaceDetails({
      name: place.name,
      address: place.formatted_address,
      placeId: place.place_id,
    });

    // Fetch place boundary from Google Maps internal data
    fetchPlaceBoundary(place.place_id);

    // Center the map
    map?.panTo(place.geometry.location!);
  };

  // Fetching place boundary using the Place ID
  const fetchPlaceBoundary = async (placeId: string) => {
    try {
      const service = new google.maps.places.PlacesService(map!);

      service.getDetails({ placeId }, (place, status) => {
        if (status === google.maps.places.PlacesServiceStatus.OK && place.geometry) {
          const bounds = new google.maps.LatLngBounds();
          if (place.geometry.viewport) {
            place.geometry.viewport.extend(bounds.getNorthEast());
            place.geometry.viewport.extend(bounds.getSouthWest());
          }

          // Attempt to get more detailed boundaries
          if (place.address_components) {
            setPolygonCoords(generateMockBoundary(place.geometry.location!)); // Generate mock boundaries
          }
        }
      });
    } catch (error) {
      console.error("Error fetching boundary:", error);
    }
  };

  // Function to generate a sample boundary (replace with real API if needed)
  const generateMockBoundary = (center: google.maps.LatLng) => {
    const lat = center.lat();
    const lng = center.lng();

    return [
      { lat: lat + 0.01, lng: lng - 0.01 },
      { lat: lat + 0.01, lng: lng + 0.01 },
      { lat: lat - 0.01, lng: lng + 0.01 },
      { lat: lat - 0.01, lng: lng - 0.01 },
    ];
  };

  return (
    <LoadScript googleMapsApiKey={API_KEY} libraries={libraries}>
      <div className="p-4">
        {/* Search Box */}
        <Autocomplete
          onLoad={(autocomplete) => (autocompleteRef.current = autocomplete)}
          onPlaceChanged={onPlaceSelected}
        >
          <input
            type="text"
            placeholder="Search for an area..."
            className="w-full p-2 border border-gray-300 rounded"
          />
        </Autocomplete>

        {/* Display Selected Place Details */}
        {placeDetails && (
          <div className="mt-4 p-3 bg-gray-100 rounded">
            <h3 className="text-lg font-semibold">{placeDetails.name}</h3>
            <p>{placeDetails.address}</p>
            <p><strong>Place ID:</strong> {placeDetails.placeId}</p>
          </div>
        )}

        {/* Map Display */}
        <div className="mt-4">
          <GoogleMap mapContainerStyle={containerStyle} center={defaultCenter} zoom={13} onLoad={setMap}>
            {/* Draw Polygon with Dashed Border */}
            {polygonCoords.length > 0 && (
              <Polygon
                paths={polygonCoords}
                options={{
                  strokeColor: "#FF0000",
                  strokeOpacity: 1,
                  strokeWeight: 2,
                  fillColor: "transparent",
                  fillOpacity: 0,
                  strokeDashArray: [5, 5], // Makes it a dashed line like Google Maps
                }}
              />
            )}
          </GoogleMap>
        </div>
      </div>
    </LoadScript>
  );
}

it would be a great help if someone can tell me how to implement this?

Share Improve this question edited Mar 30 at 14:05 Yasin Shah asked Mar 30 at 12:49 Yasin ShahYasin Shah 334 bronze badges 1
  • wait, are you unable to highlight a shape on the map with a dotted-line or focus on it with the camera? i'm not sure what problem you are trying to solve. – sparkJ Commented Mar 31 at 15:26
Add a comment  | 

1 Answer 1

Reset to default 0

map.panToBounds is likely what you're looking for. google docs here

发布评论

评论列表(0)

  1. 暂无评论