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

React Native Maps类型错误:undefined is not an object(evaluating 'this.state.departure.loc.map')

Fixing the undefined is not an object(evaluating 'this.state.departure.loc.map') Error in React Native Maps

Hey there, let's break down this frustrating error you're facing. That message tells us one clear thing: when your code tries to call map() on this.state.departure.loc, either this.state.departure is undefined, or the loc property on departure doesn't exist (so it's undefined too).

结合你提到的Google Directions API response structure, here are the most likely culprits and how to fix each one:


1. Your Initial State Isn't Properly Initialized

If you didn't set a default value for departure or departure.loc in your component's initial state, your app will try to access undefined values before the API request finishes.

Quick Fix:
Set up your state with sensible defaults so there's always something to work with while waiting for the API:

// Class component example
constructor(props) {
  super(props);
  this.state = {
    departure: { loc: [] }, // Initialize with empty loc array
    // Other state properties...
  };
}

// Functional component example with useState
const [departure, setDeparture] = useState({ loc: [] });

2. You're Parsing Google Directions Data Wrong

Looking at the API response structure you shared, Google Directions doesn't return a departure.loc field at all. You're probably mapping the raw API response to your state incorrectly.

Google stores route coordinates in two main places:

  • routes[0].overview_polyline.points: A compressed string of the entire route (use this for drawing a polyline)
  • routes[0].legs[0].steps: Individual steps with start/end coordinates (use this for markers at each stop)

Example Parsing Code:
First, install the @mapbox/polyline library to decode the compressed points string:

npm install @mapbox/polyline
# or
yarn add @mapbox/polyline

Then parse the response and update your state correctly:

import polyline from '@mapbox/polyline';

const handleDirectionsResponse = (response) => {
  if (response.routes && response.routes.length > 0) {
    // Decode the overview polyline into an array of [lat, lng] pairs
    const routeCoordinates = polyline.decode(response.routes[0].overview_polyline.points);
    
    // Update state with the parsed coordinates
    this.setState({
      departure: { loc: routeCoordinates }
    });
    
    // For functional components:
    // setDeparture({ loc: routeCoordinates });
  }
};

3. You're Not Checking for Data Before Rendering

API requests are asynchronous—your component will render before the data comes back. If you don't guard against undefined state, you'll hit this error every time.

Fix:
Add a check to make sure departure and loc exist (and are an array) before trying to map over them:

// Class component render method
render() {
  const { departure } = this.state;
  
  // Show a loading state if data isn't ready yet
  if (!departure || !Array.isArray(departure.loc)) {
    return <View><Text>Loading route...</Text></View>;
  }
  
  return (
    <MapView style={{ flex: 1 }}>
      {departure.loc.map((coord, index) => (
        <Marker
          key={index}
          coordinate={{ latitude: coord[0], longitude: coord[1] }}
        />
      ))}
    </MapView>
  );
}

// Functional component version
const YourMapComponent = () => {
  const [departure, setDeparture] = useState({ loc: [] });
  
  if (!departure?.loc || !Array.isArray(departure.loc)) {
    return <View><Text>Loading route...</Text></View>;
  }
  
  return (
    <MapView style={{ flex: 1 }}>
      {departure.loc.map((coord, index) => (
        <Marker
          key={index}
          coordinate={{ latitude: coord[0], longitude: coord[1] }}
        />
      ))}
    </MapView>
  );
};

4. You're Assigning the Wrong Data to State

Double-check where you're updating your state. If you're setting departure to the entire raw API response instead of the parsed coordinates, departure.loc will never exist.

What to Avoid:

// ❌ Wrong: Assigning the whole API response to departure
this.setState({ departure: response });

What to Do Instead:

// ✅ Correct: Assign only the parsed coordinates to departure.loc
this.setState({
  departure: {
    loc: routeCoordinates // The array you parsed from the API
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:02:02