如何在React js中使用谷歌地图方向API添加自定义标记

问题描述 投票:0回答:2

技术堆栈 - Google 地图方向 Api、React JS 等

问题陈述 - 使用谷歌地图方向 Api 绘制 3 个引脚,即起点、航路点和目的地。我能够绘制所有这些,但无法为每个添加自定义标记。任何帮助/建议将不胜感激:-

代码片段:-

import React, { Component } from "react";
import {
    withGoogleMap,
    withScriptjs,
    GoogleMap,
    DirectionsRenderer
} from "react-google-maps";

class Map extends Component {
    state = {
        directions: null
    };

componentDidMount() {
        const directionsService = new google.maps.DirectionsService();
        const origin = { lat: 40.756795, lng: -73.954298, icon: 'https://toppng.com/uploads/preview/map-marker-icon-600x-map-marker-11562939743ayfahlvygl.png' };
        const destination = { lat: 41.756795, lng: -78.954298, icon: 'https://toppng.com/uploads/preview/map-marker-icon-600x-map-marker-11562939743ayfahlvygl.png' };

   directionsService.route({
            origin: origin,
            destination: destination,
            waypoints: [{
                location: new google.maps.LatLng(42.756795, -78.954298, 'https://toppng.com/uploads/preview/map-marker-icon-600x-map-marker-11562939743ayfahlvygl.png'),
                stopover: false
            }],
            travelMode: google.maps.TravelMode.DRIVING
        },
            (result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                    this.setState({
                        directions: result
                    });
                } else {
                    console.error(`error fetching directions ${result}`);
                }
            }
   );
    }
  render() {
        const GoogleMapExample = withGoogleMap(props => (
            <GoogleMap
                defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
                defaultZoom={13}
            >
                <DirectionsRenderer
                    directions={this.state.directions}
                />
            </GoogleMap>
        ));

        return (
            <div>
                <GoogleMapExample
                    containerElement={<div style={{ height: `500px`, width: "500px" }} />}
                    mapElement={<div style={{ height: `100%` }} />}
                />
            </div>
        );
    }
}

export default Map;

谢谢

google-maps-api-3 google-maps-markers google-map-react
2个回答
1
投票

react-google-maps
有一个
Marker
组件可供您使用。

<GoogleMap
  defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
  defaultZoom={13}
>
  <DirectionsRenderer
    directions={this.state.directions}
  />
  <Marker location={{ lat: x, lng: y }} />
</GoogleMap>

0
投票

我也遇到了这个问题,我通过以下代码片段解决了它:

import {DirectionsRenderer, GoogleMap, Marker} from "@react-google-maps/api";
import {useEffect, useState} from "react";

type IProps = {
  center: google.maps.LatLngLiteral;
}

const MapComponent = ({center}: IProps) => {
  const [map, setMap] = useState<google.maps.Map | null>(null);
  const [directionsResponse, setDirectionsResponse] = useState<google.maps.DirectionsResult | null>(null);

  const origin = {lat: 35.215630, lng: 139.881960}; // 1-chōme-31 Tsurumaki, Setagaya City, Tokyo 154-0016
  const destination = {lat: 35.686960, lng: 139.749460}; // minito tower tokyo japan

  const originIcon = {
    url: "/icons/driver.png",
    scaledSize: new window.google.maps.Size(40, 40),
  };

  const destinationIcon = {
    url: "/icons/destination.png",
    scaledSize: new window.google.maps.Size(40, 40),
  };

  useEffect(() => {
    if (origin && destination) {
      void calculateRoute();
    }
  }, [origin, destination]);

  async function calculateRoute() {
    if (!origin || !destination) {
      return;
    }
    const directionsService = new window.google.maps.DirectionsService();
    const results = await directionsService.route({
      origin,
      destination,
      travelMode: window.google.maps.TravelMode.DRIVING,
    });
    setDirectionsResponse(results);
    addCustomMarkers(results);
  }

  const addCustomMarkers = (directionsResult: google.maps.DirectionsResult) => {
    if (map) {
      const myRoute = directionsResult.routes[0].legs[0];

      // Create a marker for the start location
      new window.google.maps.Marker({
        position: myRoute.start_location,
        map: map,
        icon: originIcon,
      });

      // Create a marker for the end location
      new window.google.maps.Marker({
        position: myRoute.end_location,
        map: map,
        icon: destinationIcon,
      });
    }
  };

  function clearRoute() {
    setDirectionsResponse(null);
  }

  return (
    <GoogleMap
      center={center}
      zoom={11}
      mapContainerStyle={{width: "100%", height: "100vh"}}
      options={{
        zoomControl: false,
        streetViewControl: false,
        mapTypeControl: false,
        fullscreenControl: false,
      }}
      onLoad={(map) => setMap(map)}
    >
      {/*<Marker position={origin} icon={originIcon}/>*/}
      {/*<Marker position={destination} icon={destinationIcon}/>*/}
      {directionsResponse && (
        <DirectionsRenderer
          directions={directionsResponse}
          options={{
            suppressMarkers: true, // Disable the default markers
          }}
        />
      )}
    </GoogleMap>
  );
};

export default MapComponent;

图片

© www.soinside.com 2019 - 2024. All rights reserved.