我已经能够使用静态标记实现Map。我希望将标记放在我点击地图的任何地方。我想问一下这是否可能。
到目前为止,这是我的地图组件:
import React from 'react';
import './CSS/index.css';
export default class App extends React.Component {
constructor() {
super();
this.state = {
zoom: 13,
maptype: 'roadmap',
place_formatted: '',
place_id: '',
place_location: '',
};
}
componentDidMount() {
let map = new window.google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap',
});
map.addListener('zoom_changed', () => {
this.setState({
zoom: map.getZoom(),
});
});
map.addListener('maptypeid_changed', () => {
this.setState({
maptype: map.getMapTypeId(),
});
});
let marker = new window.google.maps.Marker({
map: map,
position: {lat: -33.8688, lng: 151.2195},
});
// initialize the autocomplete functionality using the #pac-input input box
let inputNode = document.getElementById('pac-input');
map.controls[window.google.maps.ControlPosition.TOP_LEFT].push(inputNode);
let autoComplete = new window.google.maps.places.Autocomplete(inputNode);
autoComplete.addListener('place_changed', () => {
let place = autoComplete.getPlace();
let location = place.geometry.location;
this.setState({
place_formatted: place.formatted_address,
place_id: place.place_id,
place_location: location.toString(),
});
// bring the selected place in view on the map
map.fitBounds(place.geometry.viewport);
map.setCenter(location);
marker.setPlace({
placeId: place.place_id,
location: location,
});
});
}
render() {
return (
<div id='app'>
<div id='state'>
<p>Place: {this.state.place_formatted}</p>
{/* <p>Place ID: {this.state.place_id}</p>*/}
<p>Location: {this.state.place_location}</p>
<div id='pac-container'>
<input id='pac-input' type='text' placeholder='Enter a location' />
</div>
{/* <h1>State</h1>
<p>
Zoom level: {this.state.zoom}<br />
Map type: {this.state.maptype}
</p>*/}
</div>
<div id='map' />
</div>
);
}
};
&#13;
现在每当我搜索位置时,只生成lat和lang的位置。我试图制作一个onclick标记。