геолокация в React, используйте ответ-Google-карты - PullRequest
0 голосов
/ 08 июня 2018

Как изменить defaultCenter в реагировать-google-maps?Мне нужно найти свое географическое положение и изменить значения по умолчанию lat и lng.

import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";

const getLocation = () =>{
   const pos = {};
   const geolocation = navigator.geolocation;
   if (geolocation) {
      geolocation.getCurrentPosition(findLocal, showEror);
   }
   function findLocal(position){
      pos.lat = position.coords.latitude;
      pos.lng = position.coords.longitude;
   }
   function showEror(){console.log(Error)}
   return pos;
};
const myLocation = getLocation(); // object has lat and lng

Мне нужно перенести мои данные в компонент MapWithAMarker следующим образом: Сenter = {myLocation} и позиция маркера = {myLocation}

class GoogleMapCenter extends React.Component{
    render(){  
    const MapWithAMarker = withScriptjs(withGoogleMap(props =>
        <GoogleMap
            defaultZoom={10}
            defaultCenter={{ lat: -34.397, lng: 150.644 }}>
            {props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} />}
        </GoogleMap>
    ));

    return(
        <MapWithAMarker
            isMarkerShown
            googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp"
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `400px` }} />}
            mapElement={<div style={{ height: `100%` }} />}
        />
    )
  }
}
export default GoogleMapCenter;

Если я использую этот .props, он не работает.

 <MapWithAMarker
            center={this.props.myLocation}
            position={this.props.myLocation}
            isMarkerShown
            googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp"
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `400px` }} />}
            mapElement={<div style={{ height: `100%` }} />}
        />

или

        <GoogleMap
            defaultZoom={10}
            defaultCenter={this.props.myLocation}>
            {props.isMarkerShown && <Marker position={this.props.myLocation} />}
        </GoogleMap>

1 Ответ

0 голосов
/ 14 июня 2018

Свойства по умолчанию, такие как defaultCenter, могут быть установлены только как начальное состояние, center свойство может использоваться вместо этого для повторного рендеринга (центрирования) карты.

В следующем примере показано, как центрировать карту на основе текущего местоположения

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentLatLng: {
        lat: 0,
        lng: 0
      },
      isMarkerShown: false
    }
  }

  showCurrentLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => {
          this.setState(prevState => ({
            currentLatLng: {
              ...prevState.currentLatLng,
              lat: position.coords.latitude,
              lng: position.coords.longitude
            },
            isMarkerShown: true
          }))
        }
      )
    } else {
      error => console.log(error)
    }
  }


  componentDidMount() {
    this.showCurrentLocation()
  }

  render() {
    return (
      <div>
        <MapWithAMarker
          isMarkerShown={this.state.isMarkerShown}
          currentLocation={this.state.currentLatLng} />
      </div>
    );
  }
}

, где

const MapWithAMarker = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap
)((props) =>
    <GoogleMap
        defaultZoom={8}
        center={{ lat: props.currentLocation.lat, lng: props.currentLocation.lng }}
    >
        {props.isMarkerShown && <Marker position={{ lat: props.currentLocation.lat, lng: props.currentLocation.lng }} onClick={props.onMarkerClick} />}
    </GoogleMap>
)

Демо ( edit)

...