shunshun
shunshun

Reputation: 93

How to update coordinates of "showsUserLocation" marker in react native maps?

The (blue dot) marker doesn't response to user movements. I can get the current location of the user, but I can't figure how to update the location of the blue marker. I can use component and update its location, but I need to use blue dot marker because I need to have geolocator button on the top right hand side.

import React, { useState, useEffect } from "react";
import * as Location from "expo-location";
import { Dimensions, StyleSheet, Text, View } from "react-native";
import MapView, { Callout, Circle, Marker } from "react-native-maps";

export default function App() {
  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({});
      let watchID = await Location.watchPositionAsync(
        {
          accuracy: Location.Accuracy.High,
          timeInterval: 500,
          distanceInterval: 0
        },
        position => {
          setLocation(position);
        }
      );
    })();
  }, []);

  let text = "Waiting..";
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);
  }
  return (
    <View style={{ marginTop: 50, flex: 1 }}>
      {location && (
        <>
          <Text style={styles.paragraph}>
            {"lat:" + location.coords.latitude}
          </Text>
          <Text style={styles.paragraph}>
            {"long:" + location.coords.longitude}
          </Text>
          <Text style={styles.paragraph}>
            {"acurracy:" + location.coords.accuracy}
          </Text>
        </>
      )}

      <MapView
        style={styles.map}
        initialRegion={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421
        }}
        provider="google"
        showsUserLocation={true}
        followsUserLocation={true}

        // scrollEnabled={false}
      >
        {location && (
          <Marker
            coordinate={{
              latitude: location.coords.latitude,
              longitude: location.coords.longitude
            }}
          ></Marker>
        )}
      </MapView>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  },
  map: {
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height
  }
});

Thanks!

enter image description here

Upvotes: 0

Views: 1574

Answers (1)

shunshun
shunshun

Reputation: 93

Adding followsUserLocation={true} props fixed my problem.

Upvotes: 1

Related Questions