Как передать геолокации lat lng из componentDidMount в другую функцию? - PullRequest
0 голосов
/ 03 ноября 2018

Я создаю приложение React с использованием API Карт Google и API Foursquare. В настоящее время у меня есть поисковый центр Foursqaure, жестко запрограммированный в ll: "36.04,-86.74",, а затем внутри componentDidMount У меня есть console.log( Lat: $ {crd.latitude} Lng: $ {crd.longitude} );, который получает широта от местоположения пользователя.

Как я могу передать это местоположение пользователя в ll вместо жесткого кода?

Код ниже - этот раздел файла, пожалуйста, дайте мне знать, если я должен вставлять / публиковать по-другому / или ссылку репо (я предполагал, что этого будет достаточно).

// Search query to Foursquare API
  searchVenues = (query, limit) => {
    SquareAPI.search({
      ll: "36.04,-86.74", // Needs to be lat lng from user geo
      // ll: {lat: crd.latitude, lng: crd.longitude}, // doesn't work
      query: query,
      limit: limit
    }).then(res => {
      const { venues } = res.response;
      const center = { lat: 36.04, lng: -86.74 }; // this also needs to be lat lng from user geo (?)
      const markers = venues.map(venue => {
        return {
          lat: venue.location.lat,
          lng: venue.location.lng,
          isOpen: false,
          isVisible: true,
          id: venue.id
        };
      })
      this.setState({ venues, center, markers });
      // Error for foursquare API call failure
    }).catch(error => {
      // pass error message(s) to handelError()
      this.handleError(error)
    })
  }
  // After mount of App component
  componentDidMount() {
    // Pass these into Foursquare search query above
    this.searchVenues("juice+coffee", "25");

    // Geolocation snippet based on MDN's example
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };

    // Success function for current position
    const success = (pos) => {
      const crd = pos.coords;
      console.log('Your current position is:');
      console.log(`Lat: ${crd.latitude} Lng: ${crd.longitude}`);

      this.setState({ center: { lat: crd.latitude, lng: crd.longitude } })
      this.setState({ defualtCenter: { lat: crd.latitude, lng: crd.longitude } })
    }

    function error(err) {
      console.warn(`ERROR(${err.code}): ${err.message}`);
    }

    navigator.geolocation.getCurrentPosition(success, error, options);
  }
...