简体   繁体   中英

Map Centered on Current Location with a Marker? React Native Expo

I have a mapView, and I want to centre my map on the user's current location when the map screen is opened. By following the expo documentation, it should be achieved with Expo Location API. However, the documentation is unclear. I took part of the code from expo Location documentation. So, how should I integrate it in MapView in order to execute the getCurrentPositionAsync method and centre the map accordingly? Thanks for the help

import React, { useContext, useState, useEffect } from "react";
import MapView from "react-native-maps";
import styled from "styled-components";
import { Searchbar } from "react-native-paper";
import { View } from "react-native";

import * as Location from 'expo-location';

const Map = styled(MapView)`
height: 100%;
width: 100%;
`;

const SearchBarContainer= styled(View)`
padding: ${(props) => props.theme.space[3]};
position: absolute;
z-index: 999;
top: 20px;
width: 100%;
`;

export const MapScreen = ({navigation}) => {

  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

  useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
    })();
  }, []);

  return (
    <> 
    <SearchBarContainer>
      <Searchbar placeholder="location"/>
    </SearchBarContainer>
    <Map showsUserLocation={true}>
      
    </Map>
    </>
  );};

Your code is missing the region / initialRegion prop in the Map component, that's where you'll tell it to be at the location. You may also want to use a Marker to point out the specific location. Lastly you may want to consider naming the 'stated' location and the 'obtained' location different names for clarity (not sure if it affects the code as well).

    <MapView        
          region={{
              latitude: location.latitude,
              longitude: location.longitude,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }}>
          <Marker
            coordinate={location}
               >
          </Marker>
       </MapView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM