get current user location using google maps api with react native? - react-native

i'm currently working on a project using google maps api with react native, but i'm struggling to handle get current user location with redux, this is my action ,how can i fix it :
import MAPSActionTypes from "./mapsactiontypes";
export const currentlocation = () => {
return navigator.geolocation.getCurrentPosition(
(position) => {
console.log("wokeeey");
console.log(position);
{payload: position}
},
(error) => console.log(error)),
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
};

I'm not sure what you're error is exactly, but I found an issue here on doing the exact same thing. It referred to a code sample you can find here, which I've reproduced below.
import React from 'react';
import {
Alert,
Platform,
StyleSheet
} from 'react-native';
import MapView from 'react-native-maps'
const LATITUDE_DELTA = 0.01;
const LONGITUDE_DELTA = 0.01;
const initialRegion = {
latitude: -37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}
class MyMapView extends React.Component {
map = null;
state = {
region: {
latitude: -37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
},
ready: true,
filteredMarkers: []
};
setRegion(region) {
if(this.state.ready) {
setTimeout(() => this.map.mapview.animateToRegion(region), 10);
}
//this.setState({ region });
}
componentDidMount() {
console.log('Component did mount');
this.getCurrentPosition();
}
getCurrentPosition() {
try {
navigator.geolocation.getCurrentPosition(
(position) => {
const region = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
};
this.setRegion(region);
},
(error) => {
//TODO: better design
switch (error.code) {
case 1:
if (Platform.OS === "ios") {
Alert.alert("", "Para ubicar tu locación habilita permiso para la aplicación en Ajustes - Privacidad - Localización");
} else {
Alert.alert("", "Para ubicar tu locación habilita permiso para la aplicación en Ajustes - Apps - ExampleApp - Localización");
}
break;
default:
Alert.alert("", "Error al detectar tu locación");
}
}
);
} catch(e) {
alert(e.message || "");
}
};
onMapReady = (e) => {
if(!this.state.ready) {
this.setState({ready: true});
}
};
onRegionChange = (region) => {
console.log('onRegionChange', region);
};
onRegionChangeComplete = (region) => {
console.log('onRegionChangeComplete', region);
};
render() {
const { region } = this.state;
const { children, renderMarker, markers } = this.props;
return (
<MapView
showsUserLocation
ref={ map => { this.map = map }}
data={markers}
initialRegion={initialRegion}
renderMarker={renderMarker}
onMapReady={this.onMapReady}
showsMyLocationButton={false}
onRegionChange={this.onRegionChange}
onRegionChangeComplete={this.onRegionChangeComplete}
style={StyleSheet.absoluteFill}
textStyle={{ color: '#bc8b00' }}
containerStyle={{backgroundColor: 'white', borderColor: '#BC8B00'}}>
{markers.map(renderMarker)}
{children && children || null}
</ClusteredMapView>
);
}
}
export default MyMapView;

Related

Markers don't always show up in the MapView of the Map page of my react-native app

There are 4 "parceiros" (partners) registered in the database. Each partner has an address, in the model "Street Ocean View, 182". These addresses are converted to coordinates in the useCoordinates hook. But markers don't always load on the map. I searched for a solution but hard to find someone who has done the same in react-native > 0.69
/src/page/mapa/index.js
import { useState, useEffect } from 'react';
import { View, PermissionsAndroid, Image } from 'react-native';
import BarraPesquisa from '../../components/BarraPesquisa';
import MapView, { Marker } from 'react-native-maps';
import Geolocation from "react-native-geolocation-service";
import useCoordenadas from '../../hooks/useCoordenadas';
import { useNavigation } from '#react-navigation/native';
import markerIcon from '../../assets/images/marker.png';
import { estilos } from './estilos';
export default function Mapa() {
const {coordenadas, carregaCoordenadas} = useCoordenadas();
const [localizacaoAtual, setLocalizacaoAtual] = useState({});
const [permiteGPS, setPermiteGPS] = useState(false);
const [mapReady, setMapReady] = useState(false);
const navigation = useNavigation();
const geolocation = Geolocation;
const requestLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Geolocation Permission',
message: 'Can we access your location?',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === 'granted') {
console.log('Permissão para acesso à geolocalização concedida')
setPermiteGPS(true);
return true;
} else {
console.log('Permissão para acesso à geolocalização não concedida');
return false;
}
} catch (err) {
return false;
}
};
useEffect( () => {
carregaCoordenadas();
requestLocationPermission();
}, [])
useEffect( () => {
permiteGPS && geolocation.getCurrentPosition(
position => {
setLocalizacaoAtual({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
coordinates: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
});
},
error => {
console.log(error.message.toString());
},
{
showLocationDialog: true,
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
}
);
}, [permiteGPS])
useEffect(() => {
},[coordenadas])
return (
<View>
<BarraPesquisa style={estilos.searchSection} />
{ ( localizacaoAtual !== undefined &&
localizacaoAtual.hasOwnProperty('latitude') &&
localizacaoAtual.hasOwnProperty('longitude')) &&
<MapView
onMapReady={() => setTimeout(() => setMapReady(true), 10000)}
loadingEnabled = {true}
provider="google"
style={estilos.map}
initialRegion={{
latitude: localizacaoAtual.latitude,
longitude: localizacaoAtual.longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.05,
}}
>
{ coordenadas && coordenadas.map((coordenada, i) => {
return (
<Marker
key={i}
tracksViewChanges={!mapReady}
coordinate={{"latitude": coordenada.lat, "longitude": coordenada.lng}}
pinColor={"orange"}
onPress={() => {
navigation.navigate('ParceiroDetalhes', coordenada.detalhes) }}>
<Image source={markerIcon} style={{height: 35, width: 35}}/>
</Marker>
)
})
}
</MapView>
}
</View>
)
}
/src/hooks/useCoordenadas.js
import { useState } from 'react';
import { listaParceiros } from '../services/requisicoes/parceiros';
import Geocode from "react-geocode";
export default function useCoordenadas() {
const [ coordenadas, setCoordenadas ] = useState([]);
const carregaCoordenadas = async () => {
const parceiros = await listaParceiros();
let coordenadasArray = [];
Geocode.setApiKey("MY_API_KEY");
Geocode.setRegion("br");
Geocode.setLanguage("cs");
Geocode.enableDebug(true);
Promise.all(
parceiros.map((parceiro) => {
Geocode.fromAddress(parceiro.Endereco).then(
(response) => {
const location = response.results[0].geometry.location;
if(location.hasOwnProperty('lat') && location.hasOwnProperty('lng')){
coordenadasArray.push({
detalhes: parceiro,
lat: location.lat,
lng: location.lng,
});
}
},
(error) => {
console.error(error);
}
)
})).then(() => {
setCoordenadas(coordenadasArray)
}
)
}
return { coordenadas, carregaCoordenadas };
}

Getting an error while animating marker on IOS in react-native

I am getting an error while I am using busLocation.timing(newCoordinate).start() for marker animation.
animateBus = (updatedBuslocation) => {
const { busLocation } = this.state;
const newCoordinate = {
latitude: updatedBuslocation.latitude,
longitude: updatedBuslocation.longitude
};
if (Platform.OS === 'android') {
if (this.busMarker) {
this.busMarker._component.animateMarkerToCoordinate(newCoordinate, 0);
}
} else {
busLocation.timing(newCoordinate).start();
}
}
// initial bus location state is like
busLocation: new AnimatedRegion({
latitude: 0.0,
longitude: 0.0,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}),
**THE ERROR IS. =>.
busLocation.timing
is not a function**

React Native Maps-based parsing error keeps coming up when trying to end the code

I'm trying to code an iOS app, exporting it to Expo to use as an emulator. Apparently when trying to end the "render" function I get a parsing error. I also am getting a "constructor expected" error when I try to put under super.
I've tried ripping it apart, adding more middle-brackets to the end, changing up where a component goes. Nothing seems to work. Not sure if this is an Expo problem or if I just have bad code. I still need to add a Marker or two to this.. feels like it will take forever.
Code:
class App extends Component,
constructor(props){
this.state = {
position: null
};
};
componentDidMount(); {
this._getCoords();
};
_getCoords = () => {
alert=("_getCoords")
navigator.geolocation.getCurrentPosition(
(position) => {
var initialPosition = JSON.stringify(position.coords);
this.setState({position: initialPosition});
let tempCoords = {
latitude: Number(position.coords.latitude),
longitude: Number(position.coords.longitude)
}
this._map.animateToCoordinate(tempCoords, 1);
}, function (error) { alert(error) },
);
};
render(); {
return (
<MapView
style= {style.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
);`
You have some syntax errors, the correct syntax should be like this:
class App extends Component {
constructor(props) {
super(props)
this.state = {
position: null
}
}
componentDidMount() {
this._getCoords()
}
_getCoords = () => {
alert = '_getCoords'
navigator.geolocation.getCurrentPosition(
position => {
var initialPosition = JSON.stringify(position.coords)
this.setState({ position: initialPosition })
let tempCoords = {
latitude: Number(position.coords.latitude),
longitude: Number(position.coords.longitude)
}
this._map.animateToCoordinate(tempCoords, 1)
},
function(error) {
alert(error)
}
)
}
render() {
return (
<MapView
style={style.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
/>
)
}
}

How to render markers on map fetched from API?

I need your help to know how to render markers on map fetched from API.
I want to track a person's location from gps coordinates (longitude and latitude) by getting data from API.
I tried too much to recover the coordinates in the MapView but I did not arrive to do it.
This is my code :
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
export default class App extends React.Component {
mapMarkers() {
return fetch('http://first-ontheweb.com/onLineSenior/pos.php')
.then(response => response.json())
.then(responseJson => {
this.setState({
marker: responseJson.data,
});
console.log(responseJson);
return responseJson.data;
})
.catch(error => {
console.error(error);
});
}
componentDidMount() {
this.mapMarkers();
navigator.geolocation.getCurrentPosition(
position => {
console.log('getCurrentPosition Succes');
this.setState({
region: {
...this.state.region,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
},
});
this.watchPosition();
},
error => {
this.props.displayError('Error detecting your Location');
alert(JSON.stringify(error));
},
{ enableHightAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
watchPosition() {
this.watchID = navigator.geolocation.watchPosition(
position => {
console.log('Watch Position Succes');
if (this.props.followUser) {
this.map.animateToRegion(
this.newRegion(position.coords.latitude, position.coords.longitude)
);
}
},
error => {
this.props.displayError('Error detecting your location');
},
{ enableHightAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}
onRegionChange(region) {
this.setState({ region });
}
constructor(props) {
super(props);
this.state = {
region: {
latitude: -6.914744,
longitude: 107.60981,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
},
markers: [
{
latlng: { latitude: marker.latitude, longitude: marker.longitude },
},
],
};
this.onRegionChange = this.onRegionChange.bind(this);
}
render() {
return (
<MapView
style={styles.map}
showsUserLocation={true}
followUserLocation={true}
zoomEnabled={true}
//annotations={markers}
>
{this.state.markers.map((marker, index) => (
<MapView.Marker
key={index}
coordinate={marker.latlng} />
))}
</MapView>
);
}
}
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});
This is the error:
ESLint: (76:59) 'marker' is not defined. (no-undef)
So, I want to display the GPS coordinates in the MapView by getting data from API.
I think its a typo
in setState it should be markers not marker
this.setState({
markers: responseJson.data,
});
Try this code, I have changed it, now working fine
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
export default class App extends React.Component {
mapMarkers() {
return fetch('http://first-ontheweb.com/onLineSenior/pos.php')
.then(response => response.json())
.then(responseJson => {
this.setState({
markers: responseJson,
});
console.log(responseJson);
return responseJson;
})
.catch(error => {
console.error(error);
});
}
componentDidMount() {
this.mapMarkers();
navigator.geolocation.getCurrentPosition(
position => {
console.log('getCurrentPosition Succes');
this.setState({
region: {
...this.state.region,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
},
});
this.watchPosition();
},
error => {
this.props.displayError('Error detecting your Location');
alert(JSON.stringify(error));
},
{ enableHightAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
watchPosition() {
this.watchID = navigator.geolocation.watchPosition(
position => {
console.log('Watch Position Succes');
if (this.props.followUser) {
this.map.animateToRegion(
this.newRegion(position.coords.latitude, position.coords.longitude)
);
}
},
error => {
this.props.displayError('Error detecting your location');
},
{ enableHightAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}
onRegionChange(region) {
this.setState({ region });
}
constructor(props) {
super(props);
this.state = {
region: {
latitude: -6.914744,
longitude: 107.60981,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
},
markers: []
};
this.onRegionChange = this.onRegionChange.bind(this);
}
render() {
console.log('marker', this.state.markers)
return (
<MapView
initialRegion={this.state.region}
style={styles.map}
showsUserLocation={true}
followUserLocation={true}
showsMyLocationButton={true}
//annotations={markers}
>
{this.state.markers && this.state.markers.map((marker, index) => (
<MapView.Marker
key={index}
coordinate={{
latitude: Number(marker.latitude),
longitude: Number(marker.longitude),
}}
/>
))}
</MapView>
);
}
}
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});

React Native Maps - Null Object Reference

I'm following this tutorial on React Native Maps: https://www.youtube.com/watch?v=MqLC0kOqrwk&t=1s
My code is near identical to the tutors (I didn't use MapView.Markers) but I get this error: Attempt to invoke interface method 'boolean
abi19_0_0.com.facebook.react.bridge.ReadableMap.hasKey(java.lang.String)' on a null object reference
Here is my code:
import React from 'react';
import { View, Text, StyleSheet, Dimensions } from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get ('window')
const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGTITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO
export default class MapScreen extends React.Component {
constructor (props) {
super (props)
this.state = {
initialPosition: {
latitude: 0,
longitude: 0,
latitudeDelta: 0,
longitudeDelta: 0,
}
}
}
watchID: ?number = null
componentDidMount () {
navigator.geolocation.getCurrentPosition ((position) => {
var lat = parseFloat (position.coords.latitude)
var long = parseFloat (position.coords.longitude)
var initialRegion = {
latitude: lat,
longitude: long,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGTITUDE_DELTA
}
this.setState ({ initialPosition: initialRegion })
},
(error) => alert (JSON.stringify (error)),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 })
this.watchID = navigator.geolocation.watchPosition ((position) => {
var lat = parseFloat (position.coords.latitude)
var long = parseFloat (position.coords.longitude)
var lastRegion = {
latitude: lat,
longitude: long,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGTITUDE_DELTA
}
this.setState ({ initialPosition: lastRegion })
})
}
componentWillUnmount () {
navigator.geolocation.clearWatch (this.watchID)
}
render () {
return (
<MapView
style = { styles.mapContainer }
region = {this.state.initialPosition}
/>
);
}
}
Managed to get this working in a new react-native init project (RN 0.47.1, RNMaps 0.16.0) with the following added to ./android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="WHATEVERYOURAPIKEYIS" />