1

Do we have any way to show current location icon in google maps by using react google maps I could not find any such props for showing current location icon in the documentation Documtation_link. here is my component i just need to show user current location icon

  const googleMapCard= compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=-----------,
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  lifecycle({
    componentWillMount() {
      const refs = {};

      this.setState({
        bounds: null,
        markers: [],
        onMapMounted: ref => {
          refs.map = ref;
        },
        onBoundsChanged: () => {
          this.setState({
            bounds: refs.map.getBounds(),
            center: refs.map.getCenter()
          });
        },
        onSearchBoxMounted: ref => {
          refs.searchBox = ref;
        },
        onPlacesChanged: onChange => {
          const places = refs.searchBox.getPlaces();
          const bounds = new window.google.maps.LatLngBounds();
        }
      });
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    onClick={e => {
      props.onChange([e.latLng.lng(), e.latLng.lat()]);
    }}
    clickableIcons={true}
    defaultZoom={8}
    center={{ lat: props.value[1], lng: props.value[0] }}
    defaultCenter={{ lat: props.value[1], lng: props.value[0] }}
    ref={props.onMapMounted}
  >
    <SearchBox
      ref={props.onSearchBoxMounted}
      // bounds={props.bounds}
      controlPosition={window.google.maps.ControlPosition.TOP_LEFT}
      onPlacesChanged={() => {
        props.onPlacesChanged(props.onChange);
      }}
    >
      <input
        type="text"
      />
    </SearchBox>
    <Marker position={{ lat: props.value[1], lng: props.value[0] }} />
    )}
  </GoogleMap>
));

2 Answers2

3

You can use the Geolocation api. See: https://developers.google.com/maps/documentation/javascript/geolocation

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    var pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    }; 
    this.setState({ownPosition: pos})     
}

It doesn't have anything to do with react-google-maps, it's a native browser api

Uri Klar
  • 3,800
  • 3
  • 37
  • 75
0

Simpler way to write navigator-safe coordinate access, using native Geolocation Api.

navigator?.geolocation.getCurrentPosition(({coords: {latitude: lat, longitude: lng}}) => {
    const pos = {lat, lng}
    this.setState({currentPosition: pos})  
})

This uses:

  • ?. null access check - Read More
  • Destructuring
  • Alias
  • => lambda arrow
Gibolt
  • 42,564
  • 15
  • 187
  • 127