簡體   English   中英

將 Google Maps API 添加到 React 以計算兩點之間的路線

[英]Adding Google Maps API to React to calculate route between two points

我正在嘗試制作一個 React 應用程序,它顯示 map 上兩點之間的距離。

我讓它在 Javascript 和 HTML 中工作,但我無法將它轉換為 React(我是新手)。

起初我得到一個錯誤:'google'沒有定義。 我通過添加來修復它: const google = window.google;

現在我收到這些錯誤: 在此處輸入圖像描述

在此處輸入圖像描述

在此處輸入圖像描述

索引.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>

應用程序.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;

首先,我會考慮使用google-map-react而不是直接使用window.google


R.e. 您的具體錯誤:我懷疑您的document.getElementById("googleMap")正在返回null因為在初始化GoogleMapsApi組件時不會呈現<div id="googleMap"></div>

查看State 和 Lifecycle ,具體來說:

componentDidMount()方法在組件 output 被渲染到 DOM 之后運行。

componentDidMount()你的document.getElementById("googleMap")應該返回一個非null值。


我還建議查看google-map-react 的代碼,看看它是如何在那里實現的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM