【问题标题】:Here map integration using React native这里使用 React native 进行地图集成
【发布时间】:2021-06-13 19:12:18
【问题描述】:

我一直在尝试将 Here Maps 集成到我的 react 本机应用程序中,我遵循了这个“教程” 但没有成功。我认为本教程仅适用于 Expo。

Here map integration in react-native mobile app

这是我写的代码

import React from 'react';
import {
    SafeAreaView,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    useColorScheme,
    View,
    TextInput
  } from 'react-native';

import MapView,{Polyline, Marker}from 'react-native-maps';
import axios from 'axios'


class ShowMap extends React.Component{

    constructor(props){
        super(props)
        this.state = {
            startingLocation: {
                latitude: "37.025",
                longitude: "-122.023",
            },
            finishLocation: {
               latitude: "37.78825",
               longitude: "-122.4324",
            },
            region: {
                latitude: parseFloat("37.025"),
                longitude: parseFloat("-122.023"),
                latitudeDelta: 0.0922,
                longitudeDelta: 0.0421,
              },
              isLoading: true
        }
    }
            
    _getRoute = () => {
        let from_lat = parseFloat(this.state.startingLocation.latitude)
        let from_long = parseFloat(this.state.startingLocation.longitude)
        let to_lat = parseFloat(this.state.finishLocation.latitude)
        let to_long = parseFloat(this.state.finishLocation.longitude)
        let route_coordinates = []
        axios.get(`https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey={api_key_here}&waypoint0=geo!${from_lat},${from_long}&waypoint1=geo!${to_lat},${to_long}&mode=fastest;car;traffic:disabled`).then(res => {
            // here we are getting all route coordinates from API response
            res.data.response.route[0].leg[0].shape.map(m => {
                // here we are getting latitude and longitude in seperate variables because HERE sends it together, but we
                // need it seperate for <Polyline/>
                let latlong = m.split(',');
                let latitude = parseFloat(latlong[0]);
                console.log(latitude);
                
                let longitude = parseFloat(latlong[1]);
                console.log(longitude);

                routeCoordinates.push({latitude: latitude, longitude: longitude});
            })
            this.setState({
                routeForMap: routeCoordinates,
                // here we can access route summary which will show us how long does it take to pass the route, distance etc.
                summary: res.data.response.route[0].summary,
                // NOTE just add this 'isLoading' field now, I'll explain it later
                isLoading: false,
            })

        }).catch(err => {
            console.log(err)
        })
    }

    componentDidMount() {
        // when this function is finished, we will set isLoading state to false to let program know that API request has finished and now we can render the map
        this._getRoute()
      }
    
    render() {
        if(this.state.isLoading) {
            return (
              <Text>Loading...(you could also use or what ever you want to show while loading the request)</Text>
            )
          } else{
        return (
<MapView region={this.state.region}>
  <Polyline coordinates={this.state.routeForMap} strokeWidth={7} strokeColor="red" geodesic={true}/>
  <Marker coordinate={{latitude: parseFloat(this.state.startingLocation.latitude), longitude: parseFloat(this.state.startingLocation.longitude)}} title="Starting location"/>
  <Marker coordinate={{latitude: parseFloat(this.state.finishLocation.latitude), longitude: parseFloat(this.state.finishLocation.longitude)}} title="Finishlocation"/>
</MapView>
        );
      }
    }


}

const styles = StyleSheet.create({
    container: {
      ...StyleSheet.absoluteFillObject,
      height: 400,
      width: 400,
      justifyContent: 'flex-end',
      alignItems: 'center',
    },
    map: {
      ...StyleSheet.absoluteFillObject,
    },
   });

   export default ShowMap;

这是我得到的结果 Output

【问题讨论】:

    标签: javascript react-native here-api react-native-maps


    【解决方案1】:

    您在 Axios 请求 URL 的末尾缺少 &amp;legAttributes=shape

    我假设res.data.response.route[0].leg[0].shape 给出了一个错误,因为没有形状数组,因为您没有在请求 URL 中设置它,然后它会在 Axios 中捕获该错误。最终永远不会将 isLoading 设置为 false。

    最后,你的 Axios get 应该是这样的:

    axios.get(`https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey={api_key_here}&waypoint0=geo!${from_lat},${from_long}&waypoint1=geo!${to_lat},${to_long}&mode=fastest;car;traffic:disabled&legAttributes=shape`).then(res => {
    

    如果它仍然不起作用,请告诉我。

    【讨论】:

    • 非常感谢您的回答,我已经做出了您在回答中提到的更改。但在那之后,我在您编写的解决方案中编写的代码中出现错误 [ReferenceError: Can't find variable: routeCoordinates] routeCoordinates.push({latitude: latitude, longitude: longitude});虽然您已声明 let route_coordinates = [] 所以我将 let route_coordinates = [] 更改为 routeCoordinates 现在几乎一切正常,因为我在控制台中不再有错误,但我现在唯一的问题是地图显示为灰色
    • 更新我上一条评论:地图显示为灰色,因为我忘记启用 Google Maps SDK,您需要启用它,然后等待大约 5 分钟,地图会正常显示跨度>
    【解决方案2】:

    您仅将 MapView 用于展览。尝试将其用于 React native。

    React Native 中的 MapView 参考以下链接:

    React Native MapView

    【讨论】:

    • 我已经在使用 Map View 进行 react native import MapView,{Polyline, Marker} from 'react-native-maps';
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 2021-04-16
    • 2017-09-16
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    相关资源
    最近更新 更多