在这里,本机移动应用程序中的地图集成 [英] Here map integration in react-native mobile app

查看:55
本文介绍了在这里,本机移动应用程序中的地图集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在react-native项目中实现Heremap api.虽然搜索得到 https://www.npmjs.com/package/react-native-heremaps .但是没有适当的文档可以使用此库.我是本机反应的新手.请给我一些实施此建议.

I am trying to implement heremap api in react-native project.While searching got https://www.npmjs.com/package/react-native-heremaps .But there is no proper documents to use this library. I am new to react-native. Please give me some suggestions to implement this.

推荐答案

!如果您不使用expo,请发表评论,我会稍作修改!

首先,您可能已经知道您需要在 HERE开发人员网站上注册帐户.

First of all, as you probably know you need to make an account at HERE Developer webiste.

注册帐户后,您必须创建一个项目(您可以免费获得免费增值计划,该计划免费提供大量请求,如果需要,可以升级).之后,您需要为REST&生成应用程序"XYZ HUB API/CLI在您的项目页面上.这样,您将收到APP ID和APP CODE.有了这些,这里的开发人员帐户设置就完成了.

After you have made an account, you have to create a project(you can get a Freemium plan for free and it has plenty of requests available for free, upgrade if you need more). After that you need to "Generate App" for REST & XYZ HUB API/CLI at your project page. With that, you will recieve APP ID and APP CODE. With all this, HERE Developer Account setup is complete.

现在让我们跳到React Native.

Lets jump to React Native now.

首先,您需要安装一个名为 react-native-maps 的npm软件包,该软件包将用于显示HERE提供的数据.您可以在此处看到安装说明.

First of all you need to install a npm package called react-native-maps which we will use to display data that HERE provides. You can see installation instructions here.

此后,假设您已经创建了一个将显示地图的组件.您需要导入以下内容:

After this, lets assume you have already created a component that will show the map. You need to import this:

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

到此,我们的地图几乎准备就绪了.

With that we have our map almost ready.

在此示例中,我将使用 axios ,但是如果需要,您可以使用 fetch 向HERE发送请求.

I will use axios in this example but you can use fetch to make requests to HERE if you want.

因此,我们导入了axios(如果您从未使用过axios,则可以在此处了解更多信息):

So we import axios(if you never worked with it you can learn more about it here):

import axios from 'axios'

现在,您应该已经在一个州或某个地方准备好了这两个位置的坐标,并且看起来应该像这样:

Now, you should have coordinates of those two locations ready in a state or somewhere, and it should look something like this:

constructor(props){
    super(props)
    this.state = {
        startingLocation: {
            latitude: "xx.x",
            longitude: "yy.y",
        },
        finishLocation: {
           latitude: "xx.x",
           longitude: "yy.y",
        }
    }
}

以"xx.x"和"yy.y"为您想要的实际坐标.

With "xx.x" and "yy.y" being actual coordinates you want.

因此,现在有了开始和结束位置的坐标时,您可以向您的HERE API项目提出请求.就这么简单(我从此处):

So now when you have coordinates of start and finish location you can make a request to you HERE API project. It's as easy as this(I got this api from here):

// I will create a function which will call this, you can call it whenever you want
_getRoute = () => {
    // we are using parseFloat() because HERE API expects a float
    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)
    // we will save all Polyline coordinates in this array
    let route_coordinates = []
    axios.get(`https://route.api.here.com/routing/7.2/calculateroute.json?app_id=PUT_YOUR_APP_ID_HERE&app_code=PUT_YOUR_APP_CODE_HERE&waypoint0=geo!${from_lat},${from_long}&waypoint1=geo!${to_lat},${to_long}&mode=fastest;bicycle;traffic:disabled&legAttributes=shape`).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]);
            let longitude = parseFloat(latlong[1]);
            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)
    })
}

注意,这里有几件事需要注意.首先,您必须使用HERE项目中的原始APP ID和APP CODE替换APP ID和APP CODE.第二点注意,我在请求URL的末尾添加了& legAttributes = shape ,但它不在文档中.我将其放置在此处,因此折线的坐标最终具有正确的形状,如果您不放置它,它将仅以道路转弯的坐标作为响应,并且折线将越过建筑物和其他东西,看起来会很糟糕.

NOTE There are few things to note here. First is that you have to replace APP ID and APP CODE with acutal APP ID and APP CODE from your HERE project. Second note that I added &legAttributes=shape at the end of the request URL but it is not in the documentation. I put it there so Polyline coordinates acutally have a correct shape, if you don't put it, it will just respond with coordinates of road turns and that polyline will go over buildings and stuff, it will just look bad.

好.所以现在我们有了坐标来制作折线,让我们开始吧.

OK. So now we have coordinates to make a Polyline, let's do that.

<MapView>
  <Polyline coordinates={this.state.routeForMap} strokeWidth={7} strokeColor="red" geodesic={true}/>
  <Marker coordinate={{latitude: this.state.startingLocation.latitude, longitude: this.state.startingLocation.longitude}} title="Starting location"/>
  <Marker coordinate={{latitude: this.state.finishLocation.latitude, longitude: this.state.finishLocation.longitude}} title="Finishlocation"/>
</MapView>

说明:Polyline.coordinates将映射我们提供的所有坐标并绘制一条Polyline.strokeWidth就是您希望线条的粗细,strokeColor显然是线条的颜色.

Explanation: Polyline.coordinates will map through all of the coordinates that we have provided and draw a Polyline. strokeWidth is just how thick you want your line to be, and strokeColor is obviously color of a line.

现在,您应该在MapView组件中添加一个 region ,以使其知道要在地图上显示的初始区域是什么.所以我建议您做这样的事情:

Now, you should add a region to your MapView component to let it know what is the initial region you want to show on the map. So I suggest you to do something like this:

在状态下,定义一个区域字段并使它与起始位置相同,然后设置增量以使视图大一点.

In state, define a region field and make it the same coordinates as starting location, and then set delta to make a bit larger view.

// so in state just add this
region: {
  latitude: parseFloat("xx.x"),
  longitude: parseFloat("yy.y"),
  latitudeDelta: 0.0922,
  longitudeDelta: 0.0421,
}

现在,将 region = {this.state.region} 添加到MapView.

And now, add region={this.state.region} to MapView.

您现在就完成了,但是请确保每次都可以使用.您需要确保在呈现地图之前,HERE API请求已完成.我会这样:

You would be done now, but let's make sure this works every time. You need to make sure that HERE API request is complete before the map renders. I would do it like this:

// in your state define field to control if loading is finished
isLoading: true,

现在,您将在React Native提供的componendDidMount()生命周期函数中调用我们之前创建的函数 _getRoute().像这样:

Now, you would call the function _getRoute() we made before in componendDidMount() lifecycle function provided by React Native. Like this:

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()函数中控制 isLoading :

So finally a final step is to control isLoading in your render() function:

render() {
  if(this.state.isLoading) {
    return (
      <Text>Loading...(you could also use <ActivityIndicator/> or what ever you want to show while loading the request)</Text>
    )
  } else {
    // just put everything we already did here + stuff you already have
  }
}

就这样.我试图使其尽可能详细,以使您和其他需要此帮助的人可以轻松使用它.

So here it is. I tried to make it as detailed as possible to make it easy for you and other people that will need help with this.

如果有不清楚或不起作用的地方,或者您需要更多帮助,请随时询问我.我总是很乐意为您提供帮助:D

Don't ever hesitate to ask me anything if something is unclear or it's not working or you need more help! I'm always happy to help :D

这篇关于在这里,本机移动应用程序中的地图集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆