Why the onPress button doesn't send me to my current location? - react-native

What I'm trying to do is when the user clicks the position button in the map, to go to the user current location. For the location I'm using import * as Location from 'expo-location';
import React, { useState, useEffect } from 'react';
import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps';
import { StyleSheet, Image, Text, View } from 'react-native';
import * as Location from 'expo-location';
import { MaterialIcons } from '#expo/vector-icons';
import { LocationView, LocationBtn } from '../components/styles';
function Map(props) {
const [mapRegion, setMapRegion] = useState(null);
useEffect(() => {
(async () => {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
const location = await Location.getCurrentPositionAsync({});
setMapRegion({
longitude: location.coords.longitude,
latitude: location.coords.latitude,
longitudeDelta: 0.0922,
latitudeDelta: 0.0421,
});
console.log('location', location);
})();
}, []);
return (
<View style={{ flex: 1 }}>
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
mapType={props.mapType}
// showsUserLocation={true}
loadingEnabled
initialRegion={mapRegion}
userInterfaceStyle="light"
showsTraffic
>
<Marker coordinate={mapRegion}>
<Image source={require('../assets/marker.png')} style={{ height: 90, width: 90 }} />
</Marker>
</MapView>
<LocationView>
<LocationBtn onPress={() => mapRegion}>
<MaterialIcons name="my-location" size={30} color="black" style={{ alignSelf: 'center', marginTop: 13 }} />
</LocationBtn>
</LocationView>
</View>
);
}
const styles = StyleSheet.create({
map: {
height: '100%',
},
});
export default Map;
By far I have put mapRegion state which it have the current location.
When I press the button, it doesn't work.

What do you mean by going to the user location? Looking at your code, you're saving your coordinates to the mapRegion state.
The onPress prop of LocationBtn has () => mapRegion which does nothing. It's just a function that has mapRegion return value.

Related

react- native latitude and longitude error

I want to put the values of the longitude and latitude of the initial Region, the longitude and latitude obtained above, but I keep getting errors. What should I do? I don't know how.
"latitude:37,
longitude: 127,"
This part keeps getting errors.
I made
const[la,setLa]=useState("Loading...")
setLa(latitude)
...
initialRegion={{
latitude:Number(la),
then error says latitude:<<'Nan'>>..
I think latitude is string.
How can I change string to number?
import { StatusBar } from "expo-status-bar";
import React from "react";
import * as Location from "expo-location";
import { View, Text, StyleSheet, ScrollView, Dimensions} from "react-native";
import { backgroundColor } from "react-native/Libraries/Components/View/ReactNativeStyleAttributes";
import { useEffect, useState } from "react";
import MapView, { PROVIDER_GOOGLE, Marker }from "react-native-maps";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
export default function App() {
const [city, setCity] = useState("Loading...");
const [la,setLa]=useState("Loading...");
const [location, setLocation] = useState(null);
const [ok, setOk] = useState(true);
const ask = async () => {
const { granted } = await Location.requestForegroundPermissionsAsync();
if (!granted) {
setOk(false);
}
const {
coords: { latitude, longitude },
} = await Location.getCurrentPositionAsync({ accuracy: 5 });
const location = await Location.reverseGeocodeAsync(
{ latitude, longitude },
{ useGoogleMaps: false }
);
setCity(location[0].district)
};
useEffect(() => {
ask();
}, []);
return (
<>
<View style={{flex:0.16,backgroundColor:'white'}}>
<Text style={{fontSize:40,marginTop:55,marginLeft:30}}>{city}</Text>
</View>
<View style={{ flex: 1 }}>
<MapView
style={{ flex: 1 }}
provider={PROVIDER_GOOGLE}
initialRegion={{
latitude:37,
longitude: 127,
latitudeDelta: 0.00922,
longitudeDelta: 0.00321,
}}>
</MapView>
</View>
<StatusBar style="black" />
</>
);
}
const styles = StyleSheet.create({
}
);
Show MapView when location is not null like this.
<View style={{ flex: 1 }}>
yourlatitudelongitudestate && <MapView
style={{ flex: 1, marginTop: 40 }}
initialRegion={{
latitude: latitude,
longitude: longitude ,
latitudeDelta: 0.00922,
longitudeDelta: 0.00321,
}}
/>
</View>

How to go to my current location using the custom button on react-native-maps?

When the user goes to another view of map, and wants to go back to his current location, I have created a custom button. When the user clicks the button, it should go back to his current location.
import React,{ useState, useEffect} from 'react';
import MapView, {Marker, PROVIDER_GOOGLE} from 'react-native-maps';
import { StyleSheet, Image , Text, View} from 'react-native';
import * as Location from 'expo-location';
import {
LocationView ,
LocationBtn,
} from '../components/styles';
import { MaterialIcons } from '#expo/vector-icons';
const Map = (props) =>{
const [mapRegion, setMapRegion] = 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({});
setMapRegion({
longitude: location.coords.longitude,
latitude: location.coords.latitude,
longitudeDelta: 0.0922,
latitudeDelta: 0.0421
});
console.log('location', location)
})();
}, [])
return(
<View style={{ flex: 1}}>
<MapView
region={mapRegion}
provider={PROVIDER_GOOGLE}
style={styles.map}
mapType={props.mapType}
showsUserLocation={true}
showsMyLocationButton={true}
loadingEnabled={true}
initialRegion={mapRegion}
userInterfaceStyle='light'
showsTraffic={true}
>
<Marker
coordinate={mapRegion}
>
<Image source={require('../assets/marker.png')} style={{height: 90, width: 90}} />
</Marker>
</MapView>
<LocationView>
<LocationBtn
>
<MaterialIcons
name="my-location"
size={30}
color="black"
style={{alignSelf: 'center', marginTop: 13}}
/>
</LocationBtn>
</LocationView>
</View>
)
}
const styles = StyleSheet.create({
map: {
height: '100%',
},
})
export default Map;
My idea was to put onPress(mapRegion) in the <LocationBtn></LocationBtn/>(which is the custom button), and when the user clicks the button, it goes to the user current location which is in the mapReagion state
How can I make it work?
There is no option in react-native-map to go to your current location. You need to implement on your own.
Use this package https://www.npmjs.com/package/react-native-location to get your location (you can do lot more) add a marker on the map using react-native-map functions.

How to make showsMyLocationButton worked?

What I'm trying to do is center the screen view to the user location when I press a custom button and not the default button react-native-map offers. I do get the longitude and latitude but I can't seem to figure out:
How to make the custom button call the method to center the view to the coordinates I have
How to center the View all together
import React,{ useState, useEffect} from 'react';
import MapView, {Marker, PROVIDER_GOOGLE} from 'react-native-maps';
import { StyleSheet, Image , Text, View} from 'react-native';
import * as Location from 'expo-location';
import {
LocationView ,
LocationBtn,
} from '../components/styles';
import { MaterialIcons } from '#expo/vector-icons';
const Map = (props) =>{
const [mapRegion, setMapRegion] = 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({});
setMapRegion({
longitude: location.coords.longitude,
latitude: location.coords.latitude,
longitudeDelta: 0.0922,
latitudeDelta: 0.0421
});
console.log('location', location)
})();
}, [])
return(
<View style={{ flex: 1}}>
<MapView
region={mapRegion}
provider={PROVIDER_GOOGLE}
style={styles.map}
mapType={props.mapType}
showsUserLocation={true}
showsMyLocationButton={true}
loadingEnabled={true}
initialRegion={mapRegion}
userInterfaceStyle='light'
showsTraffic={true}
>
<Marker
coordinate={mapRegion}
>
<Image source={require('../assets/marker.png')} style={{height: 90, width: 90}} />
</Marker>
</MapView>
<LocationView>
<LocationBtn
>
<MaterialIcons
name="my-location"
size={30}
color="black"
style={{alignSelf: 'center', marginTop: 13}}
/>
</LocationBtn>
</LocationView>
</View>
)
}
const styles = StyleSheet.create({
map: {
height: '100%',
},
})
export default Map;
<View style={{ flex: 1}}>
Please add style justify content and align items.

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!
Adding followsUserLocation={true} props fixed my problem.

How do i get location of user before API calls?

an app I am trying to make involves a portion where nearby markers are fetched from my server.
I am sure that my location hook function works, however, it is not finishing before my API call is made to get markers near that location.
This has confused me for hours, so any help would be greatly appreciated!
import React, { useEffect, useState } from "react";
import MapView, { PROVIDER_GOOGLE, Marker } from "react-native-maps";
import { StyleSheet, View, Dimensions, Platform } from "react-native";
import useLocation from "../hooks/useLocation";
import useApi from "../hooks/useApi";
import couponsInArea from "../api/couponsInArea";
const customData = require("../assets/map_styles/day_map.json");
function MapScreen(props) {
//Here is the location hook
var location = useLocation();
const couponBaseApi = useApi(couponsInArea.getCouponBases);
//Here is the API call that needs the location
useEffect(() => {
if (location) {
couponBaseApi.request(location.latitude, location.longitude);
}
}, []);
return (
<View style={styles.container}>
<MapView
followUserLocation={true}
zoomEnabled={true}
showsUserLocation={true}
style={styles.mapStyle}
provider={PROVIDER_GOOGLE}
customMapStyle={customData}
initialRegion={{
latitude: location.latitude,
longitude: location.longitude,
latitudeDelta: 0.0158,
longitudeDelta: 0.007,
}}
>
{couponBaseApi.data.couponBases.map((report) => (
<Marker
key={report.couponBaseID}
coordinate={{
latitude: report.latitude,
longitude: report.longitude,
}}
></Marker>
))}
</MapView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
mapStyle: {
width: Dimensions.get("window").width,
height: Dimensions.get("window").height,
},
});
export default MapScreen;
The solution was that the use effect hook needed to watch for a change on location,
so
useEffect(() => {
if (location) {
couponBaseApi.request(location.latitude, location.longitude);
}
}, [location]);
Thanks everyone!