目前我有这个HTML:
import React, { Component } from 'react';
import scriptLoader from 'react-async-script-loader';
import {Segment,Button,Card ,Icon,Input} from 'semantic-ui-react';
var latt='';
var lngg='';
var myLatlng;
var marker;
var selectedLocation;
class Address extends Component {
constructor(props) {
super(props);
this.state={
}
this.initMap=this.initMap.bind(this);
this.addMarker=this.addMarker.bind(this);
this.getLocation=this.getLocation.bind(this);
this.showPosition=this.showPosition.bind(this);
}
// componentWillMount(){
// this.getLocation();
// }
showPosition(position) {
console.log(position)
latt = position.coords.latitude;
lngg = position.coords.longitude;
//alert("lattitude: "+ position.coords.latitude+" Longitide: "+position.coords.longitude);
this.initMap();
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(event => this.showPosition(event));
}
}
initMap(){
// Map options
var infowindow = new window.google.maps.InfoWindow();
var geocoder = new window.google.maps.Geocoder();
console.log(latt+" "+lngg);
console.log(parseFloat(latt)+" "+parseFloat(lngg));
var options = {
zoom:8,
gestureHandling: 'greedy',
center:{lat:latt,lng:lngg}
}
// New map
var map = new window.google.maps.Map(document.getElementById('map'), options);
myLatlng = new window.google.maps.LatLng(latt,lngg);
marker = new window.google.maps.Marker({
map: map,
position: myLatlng,
draggable: true,
});
//initial marker position(current position)
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == window.google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log(results[0].formatted_address);
selectedLocation=results[0].formatted_address;
infowindow.setContent('<h5>Your Location </h5>'+results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
//get address,lat and lng by using draggable marker
window.google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == window.google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log(results[0].formatted_address);
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
selectedLocation=results[0].formatted_address;
console.log("selected location: "+selectedLocation);
document.getElementById('selectedpos').innerHTML=selectedLocation;
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
var input = document.getElementById('pac-input');
var autocomplete = new window.google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new window.google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
// var marker = new window.google.maps.Marker({
// map: map,
// anchorPoint: new window.google.maps.Point(0, -29)
// });
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
// infowindowContent.children['place-icon'].src = place.icon;
// infowindowContent.children['place-name'].textContent = place.name;
// infowindowContent.children['place-address'].textContent = address;
infowindow.setContent('<h5>'+place.name+'</h5>'+" "+address);
infowindow.open(map, marker);
document.getElementById('selectedpos').innerHTML='<h5>'+place.name+'</h5>'+" "+address;
});
}
// Add Marker Function
addMarker(props,map){
console.log("marker pos")
var marker = new window.google.maps.Marker({
position:props.coords,
map:map,
// animation: window.google.maps.Animation.BOUNCE,
draggable:false,
icon:props.iconImage
});
// Check for customicon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check content
if(props.content){
var infoWindow = new window.google.maps.InfoWindow({
content:props.content
});
marker.addListener('click', function(){
infoWindow.open(map, marker);
});
}
}
componentWillReceiveProps({isScriptLoadSucceed}){
if (isScriptLoadSucceed) {
this.getLocation();
//this.initMap();
}
else{
alert("script not loaded")
}
}
clearField(){
console.log("clear field")
document.getElementById("pac-input").value=""
}
render() {
return (
<div >
<h4 style={{color:'grey'}}>Drag the marker to set your Loaction</h4>
<Input transparent fluid iconPosition='left' placeholder='Search...'
style={{borderLeft:'4px solid teal'}}
>
<input id="pac-input"/>
<Icon name='search' />
<Button icon='remove' attached='right' basic color='teal' onClick={this.clearField.bind(this)}/>
</Input>
<div id="map" style={{height:'350px',width:'100%'}}></div>
<Card fluid>
<Card.Content>
<Card.Header>
Selected Location
</Card.Header>
<Card.Meta>
<span className='date' id="selectedpos">
<Icon name='marker' />
Your Location
</span>
</Card.Meta>
</Card.Content>
</Card>
<Button color='teal' style={{borderRadius:'0px'}} >Save</Button>
</div>
)
}
}
export default scriptLoader(
["https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&libraries=places&sensor=false"]
)(Address)
我稍后会添加我想在相关事件上调用的函数。做这样的事情会更好吗?为什么?有什么不同吗?
<div id="forMouseEvents"
onmouseover=""
onclick=""
oncontextmenu=""
ondblclick=""
onmousemove=""
onmousedown=""
onmouseup=""
onmouseleave=""
>
</div>