google-maps-react 获取拖动端的标记位置

google-maps-react get marker position on drag end

我正在尝试弄清楚如何在拖动标记时检索标记位置。我发现了这个:Drag marker event with callback providing lat/long?

并像这样在我的应用程序上实现:

export class MapContainer extends React.Component {
  onMarkerDragEnd = evt => {
    console.log(evt);
  };

  render() {
    const style = {
      width: "100%",
      height: "300px"
    };

    let lat = this.props.lat;
    let lng = this.props.lng;

    return (
      <Map
        google={this.props.google}
        style={style}
        initialCenter={{
          lat: lat,
          lng: lng
        }}
        zoom={14}
      >
        <Marker
          onClick={this.onMarkerClick}
          draggable={true}
          onDragend={this.onMarkerDragEnd}
          name={"Current location"}
        />
      </Map>
    );
  }
}

onMarkerDragEnd 函数记录一个像这样的 evt 对象:

{onClick: undefined, draggable: true, onDragend: ƒ, name: 
"Currentlocation", map: Zf, …}
draggable: true
google:{maps: {…}}
map: Zf {gm_bindings_: {…}, __gm: uf, gm_accessors_: {…}, mapTypeId: 
"roadmap", center: _.K, …}
mapCenter:{lat: "37.122024", lng: "25.234458"}
name:"Current location"
onClick:undefined
onDragend:ƒ (evt)
__proto__:Object

我试过这样做:

onMarkerDragEnd = (evt) => {
  console.log(evt.google.maps.Marker.getPosition().lat());
}

但它return无法获取未定义的位置

那么如何从这个 returned 事件中获取标记的位置? 感谢您的帮助!

onDragend 事件侦听器函数的第三个参数包含拖动后标记的坐标。

例子

class MapContainer extends React.Component {
  state = {
    markers: [
      {
        name: "Current position",
        position: {
          lat: 37.77,
          lng: -122.42
        }
      }
    ]
  };

  onMarkerDragEnd = (coord, index) => {
    const { latLng } = coord;
    const lat = latLng.lat();
    const lng = latLng.lng();

    this.setState(prevState => {
      const markers = [...this.state.markers];
      markers[index] = { ...markers[index], position: { lat, lng } };
      return { markers };
    });
  };

  render() {
    return (
      <Map
        google={this.props.google}
        style={{
          width: "100%",
          height: "300px"
        }}
        zoom={14}
      >
        {this.state.markers.map((marker, index) => (
          <Marker
            position={marker.position}
            draggable={true}
            onDragend={(t, map, coord) => this.onMarkerDragEnd(coord, index)}
            name={marker.name}
          />
        ))}
      </Map>
    );
  }
}

我只是想补充一点,onDragEnd 对我不起作用。相反,我需要为标记事件使用带有小写字母 e 的 onDragend,如:

<Marker
        position={marker.position}
        draggable={true}
        onDragend={(t, map, coord) => this.onMarkerDragEnd(coord, index)}
        name={marker.name}
      />

我有一个简单的解决方案

<GoogleMapReact
 bootstrapURLKeys={{ key: '' }}
 defaultCenter={this.state.center}
 defaultZoom={this.state.zoom}
 yesIWantToUseGoogleMapApiInternals={true}
 onClick = {this.changeMarkerPosition}
>

然后在函数中

  changeMarkerPosition =(e)=>{
    this.setState({
    ...this.state,
      details:{
        ...this.state.details,
        lat:e.lat,
        lng:e.lng
      }
    })
  }

这将自动提供最新的 co-ordinates 并且您可以通过将其绑定到状态来相应地移动您的标记。

Complete Solution
getLocation() function initially get the current location and set on the map.
onMarkerDragEnd() function get the marker location when we drag to another place.

import React, { Component } from 'react';
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';

class Maps extends Component {
    constructor(props) {
        super(props);
        this.state = {
            markers: [
                {
                    name: "Current position",
                    position: {
                        lat: '24.914161699999998',
                        lng: '67.082216'
                    }
                }
            ]

        }
    }

    onMarkerDragEnd = (coord, index) => {
        const { latLng } = coord;
        const lat = latLng.lat();
        const lng = latLng.lng();

        this.setState(prevState => {
            const markers = [...this.state.markers];
            markers[index] = { ...markers[index], position: { lat, lng } };
            return { markers };
        });
    }

    getLocation = () => {
        if (navigator && navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(pos => {
                const coords = pos.coords;

                let newState = Object.assign({}, this.state);
                newState.markers[0].position.lat = coords.latitude;
                newState.markers[0].position.lng = coords.longitude;

                this.setState(newState);
                console.log("map", this.state.markers[0].position.lat, this.state.markers[0].position.lng)
            });
        }
    }

    componentDidMount() {
        this.getLocation()
    }

    handleSubmit = async e => {
        e.preventDefault();

        const location = {
            latitude: this.state.markers[0].position.lat,
            longitude: this.state.markers[0].position.lng
        }

    }

    render() {
        return (

            <div>
                <Map
                    google={this.props.google}
                    style={{
                        width: "100%",
                        height: "300px"
                    }}
                    zoom={14}
                    initialCenter={{ lat: this.state.markers[0].position.lat, lng: this.state.markers[0].position.lng }}
                >
                    {this.state.markers.map((marker, index) => (
                        <Marker
                            key={index}
                            position={marker.position}
                            draggable={true}
                            onDragend={(t, map, coord) => this.onMarkerDragEnd(coord, index)}
                            name={marker.name}
                        />
                    ))}
                </Map>
                <button type="submit" onClick={this.handleSubmit} >submit</button>
            </div>
        );
    }
}

export default GoogleApiWrapper({
    apiKey: 'google api key here'
})(Maps);

以上答案对我不起作用,因为 onDragEnd 在我的情况下返回 undefined

onDragend={(t, map, coord) => this.onMarkerDragEnd(coord, index)}

所以我使用下面的行

找到了 coordinates
onDragEnd={(e) => this.onMarkerDragEnd(e.nativeEvent.coordinate)}

您可以在这里找到它(可拖动标记

https://github.com/react-native-community/react-native-maps

简单示例

state = {
    region: {
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    }
}

标记

<Marker
      coordinate={this.getMapRegion()}
      draggable={true}
      onDragEnd={(e) => this.onMarkerDragEnd(e.nativeEvent.coordinate)}
      title={ "Location"}
  />

onMarkerDragEnd

onMarkerDragEnd = (coord) => {
    let newRegion = {
      latitude: parseFloat(coord.latitude),
      longitude: parseFloat(coord.longitude),
      latitudeDelta: 0.0522,
      longitudeDelta: 0.0321,
    };
    this.setState({
      region: newRegion,
    });
  };

希望对你有所帮助

centerMoved(mapProps, map) {
        console.log('args:', mapProps, map);
        console.log(map.getCenter().lat());
}