React-google-maps: How to access markers in directionsRenderer

Created on 5 May 2018  路  3Comments  路  Source: tomchentw/react-google-maps

Hello, I'm trying to connect each marker with with other specific component outside the map that if I click of the marker, then only specific component's font style will change. I'm using directionsRenderer, but have no luck of accessing markers, so I can't set onClick events. Maybe someone would be able to help me? Here is what I have. Would really appreciate any advice. I'm new with google maps api. Trying to test it out. The map is being renderer successfully.

////////////
MAP COMPONENT
////////////

/* global google */
import React, { Component } from "react";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
DirectionsRenderer
} from "react-google-maps";
import _ from "lodash";
import blackMarker from "../images/map-icon.png";

class Map extends Component {
constructor(props) {
super(props);

this.state = { markerId: 1, markerId: 2 };

}

componentDidMount() {
const DirectionsService = new google.maps.DirectionsService();

console.log("SERVICE", DirectionsService);

DirectionsService.route(
  {
    origin: this.props.origin,
    waypoints: [
      {
        location: new google.maps.LatLng(51.5048632, -0.1197457)
      },
      {
        location: new google.maps.LatLng(51.5033031, -0.1895825)
      }
    ],
    destination: this.props.destination,
    travelMode: google.maps.TravelMode.DRIVING
  },
  (result, status) => {
    console.log("Result", result);
    if (status === google.maps.DirectionsStatus.OK) {
      this.setState({
        directions: result
      });
    } else {
      console.error(`error fetching directions ${result}`);
    }
  }
);
console.log("SERVICE2", DirectionsService);

}

render() {
// const markers = this.props.markers;
console.log("MAPS", google.maps.DirectionsRenderer);

if (this.state == null) {
  return <div>Loading... </div>;
}

return (
  <div style={{ display: "flex" }}>
    <div>
      <div>This is map</div>
      <GoogleMap
        defaultZoom={5}
        defaultCenter={new google.maps.LatLng(41.85073, -87.65126)}
      >
        {this.state.directions && (
          <DirectionsRenderer
            directions={this.state.directions}
            options={{
              polylineOptions: {
                stokeColor: "#FF0000",
                strokeOpacity: 0.5,
                strokeWeight: 4
              },
              markerOptions: { icon: blackMarker },
              icon: { scale: 3 }
            }}
          />
        )}
      </GoogleMap>
    </div>
  </div>
);

}
}

export default withScriptjs(withGoogleMap(Map));

//////////
MAP RENDERER COMPONENT
//////////

import React, { Component } from "react";
import blackMarker from "../images/blackMarker.png";
import Map from "./Map";

class MapRenderer extends Component {
constructor(props) {
super(props);
this.state = {
origin: {
lat: 51.5081134,
lng: -0.1270003,
text:
"This is the starting point. From here go straight to the Golden Jubilee Bridge "
},
destination: {
lat: 51.5131132,
lng: -0.1611035,
text:
"Enjoy a walk across Oxford street and walk up until you reach Marble Arch"
}
};
}
render() {
console.log(this.props);
return (

containerElement={
style={{
position: "absolute",
width: "35%",
height: "80%"
}}
/>
}
mapElement={
style={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0
}}
/>
}
googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places"
loadingElement={
100% }} />}
markers={{ lat: 40.6976684, lng: -74.260552 }}
origin={this.state.origin}
destination={this.state.destination}
/>

style={{
padding: "2rem",
display: "flex",
justifyContent: "center",
fontSize: "20px"
}}
>
{this.state.origin.text}

style={{
padding: "2rem",
display: "flex",
justifyContent: "center",
fontSize: "20px"
}}
>
{this.state.destination.text}



);
}
}

export default MapRenderer;

Most helpful comment

I followed the idea of @AonanLi and this post in medium, see my code below:

    // use directions service to get the path
    const DirectionsService = new window.google.maps.DirectionsService();
    DirectionsService.route(
      {
        origin: new window.google.maps.LatLng(-1.4519517, -48.468732),
        destination: new window.google.maps.LatLng(-1.4743965, -48.4554105),
        waypoints: [
          { location: new window.google.maps.LatLng(-1.3762847, -48.4239654) }
        ],
        travelMode: "DRIVING",
        provideRouteAlternatives: true,
        optimizeWaypoints: true
      },
      function(response, status) {
        if (status === "OK") {
          const coords = response.routes[0].overview_path;
         // save the path to state
          self.setState({ coords });
        } else {
          window.alert("Directions request failed due to " + status);
        }
      }
// then, inside component
{this.state.coords && (
       {/* draw the path */}
          <Polyline
            path={this.state.coords}
            geodesic={true}
            options={{
              strokeColor: "#ff2343",
              strokeOpacity: 0.8,
              strokeWeight: 5,
              clickable: true
            }}
          />
        )}
       {/* set the markers as you want */}
        <Marker
          onMouseOver={this.toggle}
          onMouseOut={this.toggle}
          position={new window.google.maps.LatLng(-1.4519517, -48.468732)}
        />
        <Marker
          onMouseOver={this.toggle}
          onMouseOut={this.toggle}
          position={new window.google.maps.LatLng(-1.4743965, -48.4554105)}
        />

All 3 comments

I didn't find a way of doing it with DirectionsRenderer, so I just made a customized DirectionsRenderer using Marker and Polyline, where you could set your onClick functions.

I followed the idea of @AonanLi and this post in medium, see my code below:

    // use directions service to get the path
    const DirectionsService = new window.google.maps.DirectionsService();
    DirectionsService.route(
      {
        origin: new window.google.maps.LatLng(-1.4519517, -48.468732),
        destination: new window.google.maps.LatLng(-1.4743965, -48.4554105),
        waypoints: [
          { location: new window.google.maps.LatLng(-1.3762847, -48.4239654) }
        ],
        travelMode: "DRIVING",
        provideRouteAlternatives: true,
        optimizeWaypoints: true
      },
      function(response, status) {
        if (status === "OK") {
          const coords = response.routes[0].overview_path;
         // save the path to state
          self.setState({ coords });
        } else {
          window.alert("Directions request failed due to " + status);
        }
      }
// then, inside component
{this.state.coords && (
       {/* draw the path */}
          <Polyline
            path={this.state.coords}
            geodesic={true}
            options={{
              strokeColor: "#ff2343",
              strokeOpacity: 0.8,
              strokeWeight: 5,
              clickable: true
            }}
          />
        )}
       {/* set the markers as you want */}
        <Marker
          onMouseOver={this.toggle}
          onMouseOut={this.toggle}
          position={new window.google.maps.LatLng(-1.4519517, -48.468732)}
        />
        <Marker
          onMouseOver={this.toggle}
          onMouseOut={this.toggle}
          position={new window.google.maps.LatLng(-1.4743965, -48.4554105)}
        />

I'm trying to do same, I did try to create onClick event but I was not able to do it.

Does anyone know how to load a custom into component?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Missing typing for "Calculator", "ClusterIconStyle" and "Cluster"
shrimpy picture shrimpy  路  3Comments

Using symbol with Marker
farhan687 picture farhan687  路  3Comments

[InfoWindow] React Portals: Invariant Violation Target container is not a DOM element.
MrSaints picture MrSaints  路  3Comments

lag - google maps no smooth dragging
0x1bitcrack3r picture 0x1bitcrack3r  路  3Comments

InfoBox
PaulieScanlon picture PaulieScanlon  路  3Comments