0

So, I am new at react. I am trying to develop an app in react in which i have an array of multiple objects containing different latitude and longitude in each object. I want to calculate the distance by road between two latitudes and longitudes by using google API or anything similar. I don't want to use Haversine Formula for it.

1 Answers1

0

You can use the Distanced Matrix Service of Maps JavaScript API.

First, you need to make sure that you load the Maps JavaScript script tag in your code. Once the script is loaded, you can then call the Distance Matrix Service and pass the first coordinates from your array as array of origin then the second coordinate as array of destination. I mentioned array of origin and array of destination since the origins and destinations parameter of the Distance Matrix service requires an array of one or more coordinates. I also use states to show the value in the DOM. Please see sample code and code snippet below. Please use your API key to make the code work

import React, { Component } from "react";

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      originLat: null,
      originLng: null,
      destLat: null,
      destLng: null,
      distance: null
    };
    this.onScriptLoad = this.onScriptLoad.bind(this);
  }

  onScriptLoad() {
    let coordsArray = [
      { lat: 41.0082, lng: 28.9784 },
      { lat: 41.1082, lng: 28.9784 }
    ];
    this.setState({
      originLat: coordsArray[0].lat,
      originLng: coordsArray[0].lng,
      destLat: coordsArray[0].lat,
      destLng: coordsArray[0].lng
    });

    let service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
        origins: [{ lat: this.state.originLat, lng: this.state.originLng }],
        destinations: [{ lat: this.state.destLat, lng: this.state.destLng }],
        travelMode: "DRIVING"
      },
      (response, status) => {
        if (status !== "OK") {
          alert("Error was: " + status);
        } else {
          this.setState({
            distance: response.rows[0].elements[0].distance.text
          });
        }
      }
    );
  }

  componentDidMount() {
    if (!window.google) {
      var s = document.createElement("script");
      s.type = "text/javascript";
      s.src = `https://maps.google.com/maps/api/js?key=YOUR_API_KEY`;
      var x = document.getElementsByTagName("script")[0];
      x.parentNode.insertBefore(s, x);
      // Below is important.
      //We cannot access google.maps until it's finished loading
      s.addEventListener("load", e => {
        this.onScriptLoad();
      });
    } else {
      this.onScriptLoad();
    }
  }

  render() {
    return (
      <div style={{ width: 500, height: 500 }} id={this.props.id}>
        <label>
          Origin:({this.state.originLat},{this.state.originLng})
        </label>
        <br />
        <label>
          Destination:({this.state.destLat},{this.state.destLng})
        </label>
        <br />
        <label>Distance:{this.state.distance}</label>
      </div>
    );
  }
}

export default Map;
Pagemag
  • 2,779
  • 1
  • 7
  • 17