im试图在我的地图上创建标记列表,但是要创建一个标记,我们需要使用.marker对象,它需要指定地图。我在initmap()上获得了所有配置,并且在功能内部很容易创建标记,但是当我尝试使用诸如buttom上的"单击"之类的事件时,创建标记物,我不确定如何做它。一件事是,我决定使用ReactJ组件上的纯JS实现地图,而不是使用React-Google-Maps库。
该地图工作正常,但是我现在想如何创建标记,因为我的计划是从DB带来和数组,以此方式,它会根据事件的不同而呈现特定点。
class MapComponent extends React.Component {
componentDidMount(){
this.renderMap();
}
renderMap=()=>{
loadScript('https://maps.googleapis.com/maps/api/js?key=AIzaSyBTOonRy8VwjMLryGyfmUOAexCgrQI9m0A&callback=initMap')
window.initMap = this.initMap;
}
initMap=()=> {
let uluru = {lat: 9.024645, lng:-79.531094 }; // eslint-disable-next-line
var mapOptions = {
zoom: 17,
center: uluru,
mapTypeId: 'satellite'
};
let map = new window.google.maps.Map(document.getElementById('map'), mapOptions); // eslint-disable-next-line
}
createMarker=()=>{
console.log('works')
let marker = new window.google.maps.Marker({position: {lat: 9.024645, lng:-79.531094}, map: this.initMap.map} )
return marker
}
render(){
const { points, logged } = this.props
if(!logged) return <Redirect to='signIn' />
return(
<main>
<div id="map">
</div>
<button onClick={this.createMarker}> Click </button>
</main>
);}
}
function loadScript(url){
var index = window.document.getElementsByTagName('script')[0];
var script = window.document.createElement('script');
script.src = url;
script.async = true;
script.defer = true;
index.parentNode.insertBefore(script, index);
}
const mapStateToProps =(state)=>{
return {
points: state.firestore.ordered.points,
logged: state.firebase.auth.uid
}
}
export default compose(
connect(mapStateToProps),
firestoreConnect([
{ collection:'points' },
])
)(MapComponent)
似乎您没有在initmap函数中返回:
initMap=()=> {
let uluru = {lat: 9.024645, lng:-79.531094 }; // eslint-disable-next-line
var mapOptions = {
zoom: 17,
center: uluru,
mapTypeId: 'satellite'
};
let this.myMap = window.google.maps.Map(document.getElementById('map'), mapOptions); // eslint-disable-next-line
}
并将其称为:
createMarker=()=>{
console.log('works')
let marker = new window.google.maps.Marker({position: {lat: 9.024645, lng:-79.531094}, map: this.myMap} )
return marker
}