Google Maps Directions API with no custom library

Refresh

4 weeks ago

Views

7 time

1

I have a button which, when clicked, is supposed to render a Map with the directions API loaded (the method is called from the main component). This is not working and I keep getting "Uncaught (in promise) TypeError: Cannot read property 'defaultView' of undefined" on the console. Any ideas what´s wrong? Below are the Map component and the function (the marker exists, I have console logged it)

Map component:

import React, { Component } from 'react';
class Map extends Component {
  constructor(props) {
    super(props);
    this.onScriptLoad = this.onScriptLoad.bind(this)
  }
  onScriptLoad() {
    const map = new window.google.maps.Map(
      document.getElementById(this.props.id),
      this.props.options);
    this.props.onMapLoad(map)
  }
  componentDidMount() {
    if (!window.google) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = `https://maps.googleapis.com/maps/api/js?client=iamtheone-`;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      s.addEventListener('load', e => {
        this.onScriptLoad()
      })
    } else {
      this.onScriptLoad()
    }
  }
  render() {
    return (
      <div style={{width: "50%", height: "100vh"}}id={this.props.id}/>  
    );
  }
}
export default Map;

Click method:

  renderModal= ()=>{
    let currentMarker=this.state.currentMarker[0];
    let coordinates =currentMarker.getPosition().lat() + "" + "," + currentMarker.getPosition().lng() + "";
    let directionsDisplay = new google.maps.DirectionsRenderer;
    let directionsService = new google.maps.DirectionsService;
    const center={lat: currentMarker.getPosition().lat() , lng: currentMarker.getPosition().lng()};
    const map = new google.maps.Map('my-NewMap', center);
    console.log(map);
    directionsDisplay.setMap(map);
    function calculateAndDisplayRoute(directionsService, directionsDisplay) {
      let start = this.state.ubicacion;
      let end = coordinates;
      directionsService.route({
        origin: start,
        destination: end,
        travelMode: 'DRIVING'
      }, function(response, status) {
        if (status === 'OK') {
          directionsDisplay.setDirections(response);
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
    }
    return <div>{map}</div>
  }

0 answers