react中使用百度地图_使用React中任何提供者的地图

react中使用百度地图

There are several libraries to create Map views on React, most of them target only one provider, as the popular google-map-react and google-maps-react libraries for Google Maps.

有许多库可在React上创建地图视图,其中大多数仅针对一个提供者,例如流行的Google Maps google-map-reactgoogle-maps-react库。

But what if you want to be able to start using Bing maps? Or use OpenStreetMap when your main provider is down, or you hit some request limit? You can always wrap your different providers on some abstraction over their corresponding libraries, but there’s a better choice.

但是,如果您希望能够开始使用必应地图,该怎么办? 还是在您的主要提供商关闭或遇到一些请求限制时使用OpenStreetMap? 您总是可以将不同的提供程序包装在其相应库的某种抽象上,但是有更好的选择。

输入传单 (Enter Leaflet)

Leaflet it’s an awesome open-source map library developed by Vladimir Agafonkin. It supports a great variety of providers, really, a lot.

LeafletVladimir Agafonkin开发的一个很棒的开源地图库 。 它支持多种 提供商,确实很多

Image for post
here. 在这里

Using Leaflet, with the same code you can easily swap which one you are using by changing your tile layer.

使用Leaflet,使用相同的代码,您可以通过更改tile图层轻松地交换正在使用的代码。

A tile layer is used to load and display map layers (or other data that can be geographically represented) from our provider of choice onto our Leaflet map component.

切片图层用于将地图图层(或其他可以在地理上表示的数据)从我们选择的提供程序加载并显示到我们的传单地图组件上。

Most of the ones based in OpenStreetMap are free, and some require an API key and that you provide attribution. We’ll use MapBox in this example. It uses OpenStreetMap as a base, but in order to use it you must get an access_token here.

大多数基于OpenStreetMap的都是免费的,有些需要API密钥,并且您需要提供署名。 在此示例中,我们将使用MapBox 。 它使用OpenStreetMap作为基础,但是要使用它,您必须在此处获得access_token

创建我们的第一张地图 (Creating our first map)

To create your first map you will need an HTML file with Leaflet’s .css and .js files and a div with a specific id to attach your map to. Remember to set the width and height of the map container or it won’t work.

要创建您的第一张地图,您将需要一个包含Leaflet的.css.js文件HTML文件,以及一个带有特定iddiv ,以将地图附加到该文件。 请记住,要设置地图容器的宽度高度 ,否则将不起作用。

Then just add MapBox’s tileLayer to the map using youraccess_token and proper attribution.

然后只需使用access_token和适当的attributionMapBoxtileLayer添加到地图。

We will be also adding a marker with a popup to the map. Here’s the full example:

我们还将在地图上添加带有弹出窗口的marker 。 这是完整的示例:

// Requires a div with id="map" on a html file with leaflet's css and js.
const towerLocation = [43.385807,-8.406524];
const mymap = L.map('map').setView(towerLocation, 16);


// GET ONE in https://docs.mapbox.com/help/how-mapbox-works/access-tokens;
const ACCESS_TOKEN = "--YOUR--ACCESS--TOKEN--";
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=' + ACCESS_TOKEN, {
  maxZoom: 18,
  attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
    '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
    'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
  id: 'mapbox/streets-v11',
  tileSize: 512,
  zoomOffset: -1
}).addTo(mymap);


const marker = L.marker(towerLocation).addTo(mymap);


marker.bindPopup("<b>Tower of Hercules</b><br/>UNESCO World Heritage site");

To place our marker we need to specify a place or geographical point on the map, in this case:towerLocation. It will point to the Tower of Hercules.

要放置标记,我们需要在地图上指定一个位置或地理位置 ,在这种情况下: towerLocation 。 它将指向大力神塔

This point should be a LatLng object or equivalent. It can be as simple as an array of latitude and longitude coordinates, but in Leaflet they could be represented in any of these forms:

这一点应该是LatLng对象或等效对象。 它可以像纬度经度 坐标数组一样简单,但是在Leaflet中,它们可以用以下任何形式表示:

L.latLng([43.385807,-8.406524]);{lon: -8.406524, lat: 43.385807};{lat: 43.385807, lng: -8.406524};[43.385807,-8.406524]; // Our preferred

Using towerLocation as the map’s center the result in your browser will look like this.

使用towerLocation作为地图的中心,浏览器中的结果将如下所示。

Image for post

Looks great, right?

看起来不错吧?

在React中使用Leaflet (Using Leaflet in React)

I know I know… I said React, not vanilla JS. To work with Leaflet on a more React friendly way we will be using React-Leaflet.

我知道我知道...我说的是React,不是香草JS。 为了以一种更友好的React方式与Leaflet合作,我们将使用React-Leaflet

It provides an abstraction of Leaflet as React components. It does not replace Leaflet, only leverages React’s lifecycle methods to call the relevant Leaflet handlers.

它提供了Leaflet作为React组件的抽象。 它不会替代Leaflet,仅利用React的生命周期方法来调用相关的Leaflet处理程序。

To use it on your project you’ll need to:

要在您的项目中使用它,您需要:

  1. Install leaflet and react-leaflet:

    安装传单和react-leaflet:

    Install leaflet and react-leaflet:yarn add leaflet react-leaflet or npm install leaflet react-leaflet

    安装传单和React传单: yarn add leaflet react-leafletnpm install leaflet react-leaflet

  2. Use leaflet’s CSS, otherwise you’ll see the map with its tiles oddly distributed:

    使用传单CSS,否则您将看到地图及其图块分布奇怪的情况:

    Use leaflet’s CSS, otherwise you’ll see the map with its tiles oddly distributed:<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />

    使用LeafletCSS,否则您将看到地图及其瓷砖奇怪地分布: <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />

  3. As with the previous example set at least the height of the map’s container. In this case react-leaflet creates its own container, so you can style its CSS class like this:

    与前面的示例一样,请至少设置地图容器的高度 。 在这种情况下,react-leaflet会创建自己的容器,因此您可以像这样设置其CSS类的样式:

.leaflet-container {
width: 800px;
height: 600px;
}

With all this in place our previous example would be this component:

有了所有这些之后,我们前面的示例就是这个组件:

import React from "react";
import { Map as LeafletMap, Marker, Popup, TileLayer } from "react-leaflet";


// GET ONE in https://docs.mapbox.com/help/how-mapbox-works/access-tokens/";
const ACCESS_TOKEN = "--YOUR--ACCESS--TOKEN--";


const URL = `https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=${ACCESS_TOKEN}`;
const ATTRIBUTION =
  'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>';


const TOWER_LOCATION = [43.385807, -8.406524];


const MyMap = () => (
  <LeafletMap center={TOWER_LOCATION} zoom={16}>
    <TileLayer url={URL} attribution={ATTRIBUTION} />
    <Marker position={TOWER_LOCATION}>
      <Popup>
        <b>Tower of Hercules</b>
        <br />
        UNESCO World Heritage site
      </Popup>
    </Marker>
  </LeafletMap>
);


export default MyMap;

Not so configurable right now, but you get the idea. This will look exactly as the previous image.

现在还没有那么可配置,但是您明白了。 这将与上一张图像完全一样。

使用不同的提供程序渲染相同的地图 (Rendering the same map using different providers)

If we wanted to show our maps also using OpenStreetMap or HERE, we can just use the same <MyMap /> component, passing different map parameters (URL template and attribution) as props.

如果我们想同时使用OpenStreetMap或HERE显示地图,则可以使用相同的<MyMap />组件,并传递不同的地图参数(URL模板和归因)作为道具。

URL templates for each map type can be found on the list of providers or each provider’s page. They contain placeholder variables inside brackets that Leaflet will update or set defaults for.

每种地图类型的URL模板都可以在提供程序列表或每个提供程序的页面上找到。 它们在括号内包含占位符变量,Leaflet将为这些变量更新或设置默认值。

{s} means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; a, b or c by default, can be omitted), {z} — zoom level, {x} and {y} — tile coordinates. {r} can be used to add "@2x" to the URL to load retina tiles. You can use custom keys in the template, which will be evaluated from TileLayer options.

{s}表示可用子域之一(依次用于帮助每个域限制浏览器并行请求;子域值在选项中指定;默认情况下可以省略abc ), {z} —缩放级别, {x}{y} -平铺坐标。 {r}可用于在网址中添加“ @ 2x”以加载视网膜图块。 您可以在模板中使用自定义键,这将从TileLayer选项进行评估

Leaflet will update {x}, {y} and {z} accordingly and set defaults for the rest. We’ll use a custom key to set our tokens so we’ll need to update our MyMap component to pass any extra key to <TileLayer />. Our final code will look something like this:

传单将相应地更新{x}{y}{z} ,并设置其余的默认值。 我们将使用自定义键来设置令牌,因此我们需要更新MyMap组件以将任何额外的键传递给<TileLayer /> 。 我们的最终代码如下所示:

// Your map info
const MAPS = {
  mapbox: {
    url:
      "https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token={access_token}",
    attribution:
      'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    access_token:
      "--YOUR-MAPBOX-ACCESS-TOKEN--",
  },
  openStreetMap: {
    url: "https://{s}.tile.openstreetmap.fr/hot//{z}/{x}/{y}.png",
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Tiles style by <a href="https://www.hotosm.org/" target="_blank">Humanitarian OpenStreetMap Team</a> hosted by <a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap France</a>',
  },
  stamen: {
    url: "https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.jpg",
    attribution:
      'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  },
  HERE: {
    url: `https://1.base.maps.ls.hereapi.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?apiKey={apiKey}`,
    attribution: `Map &copy; 1987-${new Date().getFullYear} <a href="http://developer.here.com">HERE</a>`,
    apiKey: "--YOUR-HERE-API-KEY--",
  },
};


// Updated my-map.jsx


import React from "react";
import { Map as LeafletMap, Marker, Popup, TileLayer } from "react-leaflet";


const TOWER_LOCATION = [43.385807, -8.406524];


const MyMap = ({url, attribution, tileParams}) => (
  <LeafletMap center={TOWER_LOCATION} zoom={16}>
    <TileLayer url={url} attribution={attribution} {...tileParams} />
    <Marker position={TOWER_LOCATION}>
      <Popup>
        <b>Tower of Hercules</b>
        <br />
        UNESCO World Heritage site
      </Popup>
    </Marker>
  </LeafletMap>
);


export default MyMap;


// Component that prints all the maps you throw at him
const Maps = maps => (
  <div id="maps">
    {maps.map(myMap => { 
      const { url, attribution, ...tileParams } = myMap;
      return <MyMap url={url} attribution={attribution} tileParams={tileParams} />
    })}
  </div>
);


// Print the four maps


<Maps maps={Object.values(MAPS)} />

If you update the CSS to show all the maps you may have this result, with four different layers from four different providers.

如果更新CSS以显示所有地图,则可能会得到来自四个不同提供程序的四个不同层的结果。

Image for post
Note HERE also requires an api key (and doesn’t even use OpenStreetMap maps as the rest)
注意:这里还需要一个api键(甚至不使用OpenStreetMap映射作为其余部分)

As a bonus, Leaflet maps are mobile-friendly so just changing the container size to this on any of the maps:

另外,Leaflet地图是移动友好的,因此只需在任何地图上将容器大小更改为此即可:

.leaflet-container {
width: 100vw;
height: 100vh;
}

Will create a full size map view on your phone that runs smoothly.

将在您的手机上创建完整尺寸的地图视图,以使其运行流畅。

Image for post
It really feels like snappy on mobile.
在移动设备上确实感觉很活泼。

更进一步 (Going further)

With React-Leaflet you can not only use almost any provider’s maps, but print tooltips, markers, layers, paths or shapes on it.

使用React-Leaflet,您不仅可以使用几乎任何提供商的地图,还可以在其上打印工具提示,标记,层,路径或形状。

You can also combine different layers from various providers, such as weather information, Maritime Routes, or railroads.

您还可以组合来自各种提供商的不同层 ,例如天气信息 ,海事路线或铁路

Leaflet is meant to be as lightweight as possible and has hundreds of plugins that provide more functionality. The problem is that not many of them are ported to React-Leaflet (v2), so sometimes you’ll need to create your own react-leaflet components. The good part is it’s not that hard.

Leaflet尽可能轻巧,并具有数百个提供更多功能的插件 。 问题在于它们中没有很多移植到React-Leaflet(v2),因此有时您需要创建自己的react-leaflet组件。 好处是它并不难

翻译自: https://medium.com/trabe/use-maps-from-any-provider-using-react-7a0b61a24b4b

react中使用百度地图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值