Search code examples
google-maps-api-3google-maps-markersgoogle-map-react

How to add custom markers using google maps directions api in react js


Tech Stack - Google Map Directions Api, React JS, etc.

Problem Statement - Using google maps direction Api's i am drawing 3 pins i.e. origin, waypoints and destination. I am able to plot all these of these but unable to add custom markers to each of these. Any help/suggestion shall be really appreciated: -

Code Snippet: -

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;

Thanks


Solution

  • react-google-maps has a Marker component that you can use.

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