You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React.js中实现Google Route API?及代码报错排查

Fixing Google Maps Directions API Issues in Your React Code

Hey there, let's break down and fix the problems in your implementation step by step:

Key Issues Identified

  • Invalid Google Maps API URL: Your URL has typos and HTML-encoded characters that will break script loading.
  • Rendering the Wrong Component: You're trying to render <DirectionsRenderer> directly instead of your custom MapWithADirectionsRenderer component.
  • Missing State Initialization: You're calling this.setState without initializing the directions state first.
  • HTML Entity Syntax Errors: You're using &lt;/&gt; instead of valid JSX </> tags.

Corrected Code

import React from "react";
import ReactDOM from "react-dom";
import { compose, withProps, lifecycle, withState } from "recompose";
import { withScriptjs, withGoogleMap, GoogleMap } from "react-google-maps";
import { DirectionsRenderer } from "react-google-maps";

const MapWithADirectionsRenderer = compose(
  // Add state management for directions
  withState('directions', 'setDirections', null),
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyAcQjrfAudzl6Ton7GA7D-gVqOINMFE7ns&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withScriptjs,
  withGoogleMap,
  lifecycle({
    componentDidMount() {
      const { setDirections } = this.props;
      const DirectionsService = new window.google.maps.DirectionsService();
      
      DirectionsService.route(
        {
          origin: new window.google.maps.LatLng(41.85073, -87.65126),
          destination: new window.google.maps.LatLng(41.85258, -87.65141),
          travelMode: window.google.maps.TravelMode.DRIVING,
        },
        (result, status) => {
          if (status === window.google.maps.DirectionsStatus.OK) {
            setDirections(result);
          } else {
            console.error(`Error fetching directions: ${status}`, result);
          }
        }
      );
    },
  })
)(props => (
  <GoogleMap 
    defaultZoom={14} 
    defaultCenter={{ lat: 41.851655, lng: -87.651335 }} // Center between origin/destination
  >
    {props.directions && <DirectionsRenderer directions={props.directions} />}
  </GoogleMap>
));

// Render your custom map component, not DirectionsRenderer directly
ReactDOM.render(
  <MapWithADirectionsRenderer />,
  document.getElementById("root")
);

What Changed?

  1. Fixed API URL: Removed the invalid =3.exp typo, replaced &amp; with &, and ensured proper parameter formatting.
  2. Added State Management: Used withState from recompose to initialize and update the directions state (instead of relying on uninitialized this.state).
  3. Corrected Component Rendering: Now rendering MapWithADirectionsRenderer instead of the raw DirectionsRenderer.
  4. Safe Google API Access: Used window.google to ensure we're accessing the loaded Google Maps script correctly.
  5. Improved Map Center: Updated the default center to sit between your origin and destination for better visibility of the route.
  6. Fixed JSX Syntax: Replaced HTML entities with valid JSX tags.

内容的提问来源于stack exchange,提问作者Store shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:28:51