react-google-maps自定义标记图标
问题描述:
目前,我已经使用InfoModal成功地将地图组件呈现为可重用组件,但是,我没有修改标准的红色Google地图图标,并且我想创建一个自定义图标。我不确定使用ES6和JSX语法我需要做什么。我查看了反应谷歌地图问题,并试图查看是否有任何当前或更新的材料如何做到这一点(这可能很简单),但我不知道如果react-google-maps有自定义的东西标记创建插件或正确的格式。react-google-maps自定义标记图标
import React, { Component } from 'react'
import { withGoogleMap, GoogleMap, Marker, InfoWindow } from 'react-google-maps'
import { DEFAULT_MARKER } from '../../constants/mapDefaults'
const MapGoogleMap = withGoogleMap(props => (
<GoogleMap
defaultZoom={16}
center={props.center}
>
{props.markers.map((marker, index) => (
<Marker
key={index}
position={marker.position}
onClick={() => props.onMarkerClick(marker)}
>
{marker.showInfo && (
<InfoWindow onCloseClick={() => props.onMarkerClose(marker)}>
<div>{marker.infoContent}</div>
</InfoWindow>
)}
</Marker>
))}
</GoogleMap>
))
export default class Map extends Component {
state = {
center: {
lat: 28.3421135,
lng: -80.6149092
},
markers: [
{
position: new google.maps.LatLng(28.3431165, -80.6135908),
showInfo: false,
infoContent: (
<svg
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
>
<path
d="M3.5 0c-1.7 0-3 1.6-3 3.5 0 1.7 1 3 2.3 3.4l-.5 8c0
.6.4 1 1 1h.5c.5 0 1-.4 1-1L4 7C5.5 6.4 6.5 5 6.5
3.4c0-2-1.3-3.5-3-3.5zm10 0l-.8 5h-.6l-.3-5h-.4L11
5H10l-.8-5H9v6.5c0 .3.2.5.5.5h1.3l-.5 8c0 .6.4 1 1 1h.4c.6 0
1-.4 1-1l-.5-8h1.3c.3 0 .5-.2.5-.5V0h-.4z"
/>
</svg>
)
}, DEFAULT_MARKER
]
}
handleMarkerClick = this.handleMarkerClick.bind(this);
handleMarkerClose = this.handleMarkerClose.bind(this);
handleMarkerClick (targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: true
}
}
return marker
})
})
}
handleMarkerClose (targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: false
}
}
return marker
})
})
}
render() {
return (
<MapGoogleMap
containerElement={
<div style={{ height: `500px` }} />
}
mapElement={
<div style={{ height: `500px` }} />
}
center={this.state.center}
markers={this.state.markers}
onMarkerClick={this.handleMarkerClick}
onMarkerClose={this.handleMarkerClose}
/>
)
}
}
答
标记传播运算符在key = {index}上方缺失。这是正确的代码。该图标本身在另一个名为mapDefaults.js的文件中定义,如果有人遇到此问题,请不要犹豫与我联系。
<Marker
{...marker}
key={index}
position={marker.position}
onClick={() => props.onMarkerClick(marker)}
>
嗨,我刚开始尝试自定义图标。我看到你用'infoContent'传递了svg来管理这个。同样不会返回新图标。仍然是旧的。你能解释一下你如何解决这个问题吗?谢谢 – Neovea
@Neovea没问题我通过给标记本身一个图标属性并将它作为字符串或作为SVG路径传递给它自定义图标。 infoContent适用于InfoWindow,不适用于标记本身。 'const的标记物= [{ 位置 :{纬度:28.3422,经度:-80.6112}, 图标:{ 路径:“M24.5 9H-8.1升-2.9-7.7C13.4 1.1 13.2 1 13 1C -0.2 0-0.4 0.1-0.5 0.3L9.6 9H1.5C1'//由于缺少允许的字符,这不是正确的路径。 } },//或 { 位置:{纬度:28.3422,经度:-80.6112}, 图标:importedIcon } ]' – Franklin