大家好,我正在尝试在react.js中实现谷歌地图,地图显示得很好,但是当我尝试显示我的标记时,什么都没有显示。如果我删除LAT值和long值,那么标记将显示在地图的顶部。但是如果我向它添加lat和long值,它就会停止显示。有人能帮帮忙吗?
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import marker from './marker.png';
import { geolocated } from 'react-geolocated';
const AnyReactComponent = ({ text }) => (
<div>
<img src={marker} style={{ height: '50px', width: '50px' }} />
</div>
);
export default class Map extends Component {
static defaultProps = {
zoom: 11,
};
Componentwillmount() {
console.log(this.props.center.latitude);
}
render() {
return (
<div className="google-map" style={{ width: '100%', height: '2000px', backgroundColor: 'red' }}>
<GoogleMapReact
options={{
styles:ExampleMapStyles
}}
center={this.props.center} defaultZoom={this.props.zoom}>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text={'Kreyser Avrora'}
/>
</GoogleMapReact>
</div>
);
}
}发布于 2019-11-01 17:59:40
文档显示您可以使用<AnyReactCompenent/>,如果您想要拥有自己的标记或文本,可以使用它。但是,如果您希望使用默认标记,则必须将其作为属性传递给<GoogleMapReact></GoogleMapReact>组件。文档提到‘您可以使用onGoogleApiLoaded访问Google Maps地图和地图对象,在这种情况下,您需要将yesIWantToUseGoogleMapApiInternals设置为true’。这只是意味着添加属性的名称,而不是像我在我的属性中那样传递一个值。从自述文件中的描述可能不能完全清楚,但实际上,map参数是maps API对象(当然,Map是当前的Google Map实例)。因此,您应该使用renderMarkers = (map, maps) => {}函数将两者都传递到方法中。
您可以尝试这样做:
import React, { Fragment } from 'react';
import GoogleMapReact from 'google-map-react';
const GoogleMaps = ({ latitude, longitude }) => {
const renderMarkers = (map, maps) => {
let marker = new maps.Marker({
position: { lat: latitude, lng: longitude },
map,
title: 'Hello World!'
});
return marker;
};
return (
<Fragment>
<div style={{ height: '50vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: 'YOUR KEY' }}
defaultCenter={{ lat: latitude, lng: longitude }}
defaultZoom={16}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
>
</GoogleMapReact>
</div>
</Fragment>
);
};
export default GoogleMaps;发布于 2019-01-22 05:02:45
我认为你需要回答的主要问题是:你的中心支柱是什么?我在沙箱中使用了你的代码,并做了一些小调整:我在你的标记应该呈现的地方使用了相同的经度/经度,以便一目了然地看到它是否真的显示了。它就是:https://codesandbox.io/s/00p1ry2v0v
export default class Map extends Component {
static defaultProps = {
zoom: 11,
center: {
lat: 49.955413,
lng: 30.337844
}
};
render() {
const mapStyles = {
width: "100%",
height: "100%"
};
return (
<div
className="google-map"
style={{ width: "100%", height: "2000px", backgroundColor: "red" }}
>
<GoogleMapReact
style={mapStyles}
center={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={49.955413}
lng={30.337844}
text={"Kreyser Avrora"}
/>
</GoogleMapReact>
</div>
);
}
}因此,请确保以适当的初始中心位置开始地图。:)
https://stackoverflow.com/questions/54297472
复制相似问题