我要做的是显示从地图上的某些移动设备中挑选的位置。 有关位置的数据在那里..
我需要的是根据从服务器收到的数据在地图上添加标记。
假设我已将位置数据({Lat,Lang})设置为状态标记 然后我如何添加它以在地图中显示。
我的地图代码如下!
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
const AnyReactComponent = ({ text }) => <div>{text}</div>;
class MyClass extends Component {
constructor(props){
super(props);
}
render() {
return (
<GoogleMapReact
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
style={{height: '300px'}}
>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text={'Google Map'}
/>
</GoogleMapReact>
);
}
}
MyClass.defaultProps = {
center: {lat: 59.95, lng: 30.33},
zoom: 11
};
export default MyClass;
&#13;
此代码来自答案Implementing google maps with react
使用过的npm包: - google-map-react
答案 0 :(得分:3)
您可以尝试:
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
const AnyReactComponent = ({ img_src }) => <div><img src={img_src} className="YOUR-CLASS-NAME" style={{}} /></div>;
class MyClass extends Component {
constructor(props){
super(props);
this.state = {
markers: [],
}
}
componentDidMount(){
// or you can set markers list somewhere else
// please also set your correct lat & lng
// you may only use 1 image for all markers, if then, remove the img_src attribute ^^
this.setState({
markers: [{lat: xxxx, lng: xxxx, img_src: 'YOUR-IMG-SRC'},{lat: xxxx, lng: xxxx, img_src: 'YOUR-IMG-SRC' },{lat: xxxx, lng: xxxx, img_src: 'YOUR-IMG-SRC'}],
});
}
render() {
return (
<GoogleMapReact
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
style={{height: '300px'}}
>
{this.state.markers.map((marker, i) =>{
return(
<AnyReactComponent
lat={marker.lat}
lng={marker.lng}
img_src={marker.img_src}
/>
)
})}
</GoogleMapReact>
);
}
}
MyClass.defaultProps = {
center: {lat: 59.95, lng: 30.33},
zoom: 11
};
如果这有错误,请在此处显示,然后我们可以稍后修复
===========
标记点击事件的新增示例
markerClicked(marker) {
console.log("The marker that was clicked is", marker);
// you may do many things with the "marker" object, please see more on tutorial of the library's author:
// https://github.com/istarkov/google-map-react/blob/master/API.md#onchildclick-func
// Look at their examples and you may have some ideas, you can also have the hover effect on markers, but it's a bit more complicated I think
}
render() {
return (
<GoogleMapReact
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
style={{height: '300px'}}
>
{this.state.markers.map((marker, i) =>{
return(
<AnyReactComponent
lat={marker.lat}
lng={marker.lng}
img_src={marker.img_src}
onChildClick={this.markerClicked.bind(this, marker)}
/>
)
})}
</GoogleMapReact>
);
}
再一次,在这里发布一些错误,如果有的话^^!
答案 1 :(得分:1)
小心点。您说react-google-map
但您正在使用google-map-react
。这是两个不同的包。不要混淆他们的文档。
我在个人项目中使用google-map-react
。您可以在此处查看代码:https://github.com/BrodaNoel/devseverywhere/blob/master/src/pages/AnalyticsPage/AnalyticsPage.jsx#L227