简体   繁体   中英

Adding Google Maps API to React to calculate route between two points

I'm trying to make an React app, that shows the distance between two points on a map.

I got it to work in Javascript and HTML, but i'm having trouble converting it to React (I'm new).

At first i got an error: 'google' is not defined. i fixed it by adding: const google = window.google;

Now i'm getting these errors: 在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
 
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

    <!-- GOOGLE API  -->
    <script src="https://maps.googleapis.com/maps/api/js?key=MY_GOOGLE_MAPS_API_KEY&libraries=places"></script>
    <!-- BOOTSTRAP -->
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>

  </body>
</html>

App.js:

import logo from "./logo.svg";
import "./App.css";
import GoogleMapsApi from "./GoogleMapsApi";

function App() {
  return (
    <>
      <GoogleMapsApi/>
     
    </>
  );
}

export default App;

GoogleMapsApi.js:

import React from "react";

import $ from "jquery";

const google = window.google;

const GoogleMapsApi = () => {

  //set map options
  // start pos
  const myLatLng = { lat: 51.5, lng: -0.1 };
  const mapOptions = {
    center: myLatLng,
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  };

  //create map
  const map = new google.maps.Map(
    document.getElementById("googleMap"),
    mapOptions
  );

  //create a DirectionsService object to use the route method and get a result for our request
  const directionsService = new google.maps.DirectionsService();

  //create a DirectionsRenderer object which we will use to display the route
  const directionsDisplay = new google.maps.DirectionsRenderer();

  //bind the DirectionsRenderer to the map
  directionsDisplay.setMap(map);

  //define calcRoute function
  function calcRoute() {
    //create request
    const request = {
      origin: document.getElementById("from").value,
      destination: document.getElementById("to").value,
      travelMode: google.maps.TravelMode.DRIVING, //WALKING, BYCYCLING, TRANSIT
      unitSystem: google.maps.UnitSystem.METRIC,
    };

    //pass the request to the route method
    directionsService.route(request, function (result, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        //Get distance and time
        $("#output").html(
          "<div class='alert-info'>From: " +
            document.getElementById("from").value +
            ".<br />To: " +
            document.getElementById("to").value +
            ".<br /> Driving distance: " +
            result.routes[0].legs[0].distance.text +
            ".<br />Duration: " +
            result.routes[0].legs[0].duration.text +
            ".</div>"
        );

        //display route
        directionsDisplay.setDirections(result);
      } else {
        //delete route from map
        directionsDisplay.setDirections({ routes: [] });
        //center map in London
        map.setCenter(myLatLng);

        //show error message
        $("#output").html(
          "<div class='alert-danger'>Could not retrieve driving distance.</div>"
        );
      }
    });
  }

  const x = document.getElementById("from");

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function showPosition(position) {
    // Use this to show in app

      x.innerHTML = "Latitude: " + position.coords.latitude +
      "<br>Longitude: " + position.coords.longitude;

    document.getElementById("from").value =
    position.coords.latitude + ", " + position.coords.longitude;
  }

  return (
    <>
      <div className="App">
        <div class="jumbotron">
          <div class="container-fluid">
            <h1>Distance between cities App.</h1>
            <p>Our app will help you calculate travelling distances.</p>
            <form class="form-horizontal">
              <div class="form-group">
                <label for="from" class="col-xs-2 control-label">
                  From:
                </label>
                <div class="col-xs-10">
                  <input
                    type="text"
                    id="from"
                    placeholder="Origin"
                    class="form-control"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="to" class="col-xs-2 control-label">
                  To:
                </label>
                <div class="col-xs-10">
                  <input
                    type="text"
                    id="to"
                    placeholder="Destination"
                    class="form-control"
                  />
                </div>
              </div>
            </form>

            {/* GET LOCATION IN LAT AND LONG */}
            <div class="col-xs-offset-2 col-xs-10">
              {/* Get currnet */}
              <button class="btn btn-info btn-lg" onClick={getLocation()}>
                Try It
              </button>

              <p id="demo"></p>
            </div>

            <div class="col-xs-offset-2 col-xs-10">
              <button class="btn btn-info btn-lg" onClick={calcRoute()}>
                Submit
              </button>
            </div>
          </div>
          <div class="container-fluid">
            <div id="googleMap"></div>
            <div id="output"></div>
          </div>
        </div>
      </div>
    </>
  );
};

export default GoogleMapsApi;

Foremost, I would consider using google-map-react instead of using window.google directly.


R.e. your specific error: I suspect your document.getElementById("googleMap") is returning null because <div id="googleMap"></div> won't have been rendered when the GoogleMapsApi component is initialized.

Review State and Lifecycle , specifically:

The componentDidMount() method runs after the component output has been rendered to the DOM.

Inside componentDidMount() your document.getElementById("googleMap") should return a non- null value.


I also recommend looking at the code for google-map-react to see how it is implemented there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM