-2

Tech Stack - Google Map Directions 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;

谢谢

4

1 回答 1

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>
于 2021-05-28T05:45:15.813 回答