reactjs - 在传单矩形内添加文本
问题描述
我正在使用以下代码在leaflet
地图中创建一个矩形。
const rectangles = [[51.49, -0.08], [51.5, -0.06]]
<Rectangle key={key} bounds={rectangle} color="green">
</Rectangle>
我想在矩形内添加一个文本,比如矩形的标签有没有办法做到这一点?
我正在为此使用react-leaflet库。
解决方案
要在地图上书写,我们可以使用Leaflet 库中添加到 React-Leaflet Marker组件的DivIcon 。
使用 HTML 创建一个 DivIcon
ADivIcon
是一个可以包含 HTML 而不是图像的图标。我们将导入Leaflet
库并DivIcon
使用我们想要的文本创建一个。
import L from 'leaflet';
const text = L.divIcon({html: 'Your HTML text here'});
将 DivIcon 添加到标记
DivIcon
创建完成后,我们将其添加到放置在 a 中心的 Marker中Polygon
。
import React from 'react';
import L from 'leaflet';
import { Marker, Polygon } from 'react-leaflet';
const PolygonWithText = props => {
const center = L.polygon(props.coord).getBounds().getCenter();
const text = L.divIcon({html: props.text});
return(
<Polygon color="blue" positions={props.coords}>
<Marker position={center} icon={text} />
</Polygon>
);
}
export default PolygonWithText
将标记添加到地图
最后,我们将Polygon
、Marker
和DivIcon
加到 aMap
中。
import React, { Component } from 'react';
import {Map, TileLayer} from 'react-leaflet';
import PolygonWithText from './PolygonWithText';
class MyMap extends Component {
render () {
return (
<Map center={[20.75, -156.45]} zoom={13}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<PolygonWithText text="MyText" coords={[...]} />
</Map>
}
}
export default MyMap;
推荐阅读
- python - 有趣的 xlwings 问题:脚本在 Python 中有效,但在 Excel 中无效
- php - 如何将变量传递给注解或 yaml?
- ios - addSublayer 不显示图像
- ruby-on-rails - 在 RoR 中使用数据库结果
- android - 未在 RecyclerView Android 中加载的项目
- typescript - 带有对象的打字稿函数重载
- c++ - 类之间的双链转换
- c++ - Excel VBA C++ .dll
- javascript - 如何获得 jquery 滑块反馈?
- java - 为什么 AnnotationMetadata 基于 ASM 而不是 Java 反射