How I set Markers in React Native Mapview - javascript

I'm using react-native-maps, I have map showing and also my current
latitude and longitude but I don't know how to show the marker in the map with latitude and longitude.
Code for lat and long:
callLocation(that){
navigator.geolocation.getCurrentPosition(
(position) => {
const currentLongitude = position.coords.longitude;
const currentLatitude = position.coords.latitude;
that.setState({ currentLongitude:currentLongitude });
that.setState({ currentLatitude:currentLatitude });
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
that.watchID = navigator.geolocation.watchPosition((position) => {
console.log(position);
const currentLongitude = position.coords.longitude;
const currentLatitude = position.coords.latitude;
that.setState({ currentLongitude:currentLongitude });
that.setState({ currentLatitude:currentLatitude });
});}
Code for Map:
<View style={styles.container}>
<MapView
style={styles.map}
initialRegion={{
latitude: this.state.currentLatitude,
longitude: this.state.currentLongitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}>
</MapView>
</View>

Working example:
<MapView provider={Platform.OS === 'android' ? PROVIDER_GOOGLE : PROVIDER_DEFAULT} // remove if not using Google Maps
style={{width: '100%', height: FULL_SH*0.51, marginTop: 65*SH}}
initialRegion={{
latitude: this.state.myLat ? this.state.myLat : 38.4555,
longitude: this.state.myLon ? this.state.myLon : 27.1199,
latitudeDelta: 0.015,
longitudeDelta: 0.0121}}>
<MapView.Marker
coordinate={{latitude: 38.4555, longitude: 27.1199}}
title={'Deneme'}
/>
<MapView.Marker
onPress={() => this.setState({visible: true}) + setTimeout(() => alert(this.state.visible), 200)}
description={'güzel mekan'}
coordinate={{latitude: 38.4555, longitude: 27.1129}}
title={'Deneme'}/>
</MapView>

You should use the Marker component.
Example:
import { MapView, Marker } from 'react-native-maps';
<MapView
style={styles.map}
initialRegion={{
latitude: this.state.currentLatitude,
longitude: this.state.currentLongitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
>
<Marker
coordinate={{latitude: 40.741075, longitude: 74.0003317}}
title={'title'}
description={'description'}
/>
</MapView>

Related

react-native not updating MapView initialRegion with react-native-geolocation-service

I would like to update my map to show the user location. Using the code below, I get a world map not a map of the UK, which is what the latitude and longitude should show, can anyone help?
const [location, setLocation] = useState({
initialPosition: {
latitude: 0,
longitude: 0,
latitudeDelta: 0,
longitudeDelta: 0,
},
});
const getLocationPermissions = async () => {
const granted = await request(
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
}),
{
title: 'DemoApp',
message: 'App would like access to your location ',
}
);
return granted === RESULTS.GRANTED;
};
useEffect(() => {
//  check permission
const isGranted = getLocationPermissions();
if (isGranted) {
// get location
Geolocation.getCurrentPosition((info) => {
let lat = info.coords.latitude;
let long = info.coords.longitude;
// update state with location,latitude: 52.62869394486038
//longitude: -1.9794797216434805
var initialRegion = {
latitude: lat,
longitude: long,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
};
});
} else {
console.log('error');
}
}, []);
return (
<View style={styles.container}>
<MapView style={styles.map} initialRegion={location.initialPosition} />
</View>
);
I am guessing you are using react-native-maps MapView Component, it has a showsUserLocation boolean property.
<MapView
style={styles.map}
showsUserLocation={true}
initialRegion={location.initialPosition}
/>
Perhaps this would resolve it?
After retrieve user location from device, animate map to that region.
import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import MapView from "react-native-maps";
const App = () => {
const mapRef = React.useRef(null);
React.useEffect(() => {
// Below are mocked location in UK. Retrieve real location
// from device with Geoocation API
// latitude: 52.62869394486038
//longitude: -1.9794797216434805
const userRegion = {
latitude: 52.62869394486038,
longitude: -1.9794797216434805,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
};
mapRef.current?.animateToRegion(userRegion);
}, []);
return (
<View style={styles.container}>
<MapView
ref={mapRef}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
style={styles.mapStyle}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingTop: 10,
backgroundColor: "#ecf0f1",
},
mapStyle: {
...StyleSheet.absoluteFillObject,
},
});
export default App;
Working example snack.
https://snack.expo.dev/#emmbyiringiro/9f04a3

How to show multiple Map marker in map in react-native?

I have created an application. My requirement is that when I enter any city name and skills in TextInput in map multiple marker return.
const GetJob =async()=>{
await fetch('https://thejoblocator.co.uk/api/RestJobs',{
method:'post',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
longitude:73.0479,
latitude:33.6844,
keyword:'web Development'
})
}).then(res=>res.json())
.then(result=>{
console.log(result)
}).catch(err=>{
console.log("Get Job error is ",err)
})
}
<MapView
provider={PROVIDER_GOOGLE} // remove if not using Google Maps
style={styles.map}
region={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
}}
>
<Marker
coordinate={{
latitude: LATITUDE,
longitude: LONGITUDE,
}}
image={require('../assets/map_marker.png')}
title="Test Title"
description="This is the test description"
>
</Marker>
</MapView>
Save the response data in the state and map the state to render multiple markers.
const [data, setData] = useState([])
const GetJob =async()=>{
await fetch('https://thejoblocator.co.uk/api/RestJobs',{
method:'post',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
longitude:73.0479,
latitude:33.6844,
keyword:'web Development'
})
}).then(res=>res.json())
.then(result=>{
console.log(result)
setData([...result]) // result must be an array..
}).catch(err=>{
console.log("Get Job error is ",err)
})
}
return (
<MapView
provider={PROVIDER_GOOGLE} // remove if not using Google Maps
style={styles.map}
region={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
}}
>
{
data && data.length ? data.map((item) => {
return (
<Marker
coordinate={{
latitude: item.LATITUDE,
longitude: item.LONGITUDE,
}}
image={require('../assets/map_marker.png')}
title="Test Title"
description="This is the test description"
/>
)
}) : null
}
</MapView>
)

filter marker based on radius react native

I'm trying to display markers based on radius and I'm unable to develop a logic for that. My locations for markers come from firestore geopoint. I have successfully filter the marker based on category from my firestore but i'm unable filter it by maximum distance radius
MY problem: I dont know how to use radius property and where to put that property and based on radius how to filter the markers
class mapView extends Component {
constructor() {
super()
this.state = {
users:[],
initialPosition: {
latitude: -6.64064,
longitude: 106.8273983,
latitudeDelta: 0,
longitudeDelta: 0
},
}
}
getLocation(){
Geolocation.getCurrentPosition(
(position) => {
var lat = position.coords.latitude
var long = position.coords.longitude
var initialRegion ={
latitude: lat,
longitude: long,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}
this.setState({initialPosition: initialRegion})
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
fetchRequests(){
this.subscriber = firebase.firestore()
.collection("users").onSnapshot(docs => {
let users = []
docs.forEach(doc => {
users.push(doc.data())
})
this.setState({users})
console.log(users)
})
}
componentDidMount() {
this.props.fetchUser();
this.fetchRequests();
this.getLocation();
}
render() {
return (
<View style={styles.container}>
<MapView
showsUserLocation={true}
provider={PROVIDER_GOOGLE}
style={styles.map}
initialRegion={this.state.initialPosition}>
{this.state.users.filter(element => element.golDarah === this.props.currentUser.golDarah && element.geo_point.latitude
!== this.props.currentUser.geo_point.latitude && element.locationOn === true )
.map((user, idx) => <Marker
key={idx}
coordinate={{latitude: user.geo_point.latitude, longitude: user.geo_point.longitude}}
>
<Callout>
<View style={{height: 0.1 * windowHeight()}}>
<Text>Nama: {user.name}</Text>
<Text>Golongan Darah: {user.golDarah}</Text>
<TouchableOpacity onPress={()=>{Linking.openURL(`${user.noHp}`)}}>
<Text>No HP:{user.noHp}</Text>
</TouchableOpacity>
</View>
</Callout>
</Marker>)}
</MapView>
</View>
);
}
}

React Native Map : How to fit Polyline coordinates to screen?

I am working with react native map and i used polyline and Marker but when i display polyline to map it not fit to screen its just shows some part of line in screen other i have to scroll then i see, so how to fit polyline coordinatin inside current screen .
But i want to make polyline look it like this. so how can i do it
here is my code look likes.
<MapView
style={styles.mapStyle}
provider={PROVIDER_GOOGLE}
minZoomLevel={0}
paddingAdjustmentBehavior="automatic"
ref={(ref) => {
this.mapRef = ref;
}}
onLayout={() =>
this.mapRef.fitToCoordinates(this.state.cord, {
edgePadding: {top: 50, right: 10, bottom: 10, left: 10},
animated: false,
})
}
onMapReady={this.onMapReadyHandler.bind(this)}
showsUserLocation={true}
fitToElements={true}
region={{
latitude: this.state.start[0],
longitude: this.state.start[1],
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
initialRegion={{
latitude: this.state.start[0],
longitude: this.state.start[1],
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}>
<Circle
center={{
latitude: this.state.start[0],
longitude: this.state.start[1],
}}
radius={40}
strokeColor={'blue'}
strokeWidth={6}
fillColor={'#fff'}
zIndex={1}
/>
{speed.map((d) =>
d.segments.map((c, i) => (
<Polyline
key={i}
coordinates={c.coordinates.map((c) => ({
latitude: c[0],
longitude: c[1],
}))}
strokeColor={c.color}
strokeWidth={6}></Polyline>
)),
)}
</MapView>
Thanks in advance
There is a solution to your problem. You have to average the sets of location data.
Here is the sample code.
let coords=[{latitude:28.97979,longitude:73.386429864}, {latitude:28.32243,longitude:73.329437204}, {latitude:28.244234,longitude:73.32482894}, {latitude:28.686976,longitude:73.2342056}, {latitude:28.23325235,longitude:73.83562325}];
let sumLat = coords.reduce((a, c) => { return parseFloat(a) + parseFloat(c.latitude)}, 0);
let sumLong = coords.reduce((a, c) => { return parseFloat(a) + parseFloat(c.longitude)}, 0);
let avgLat = (sumLat / coords.length) || 0;
let avgLong = (sumLong / coords.length) || 0;
setRegion({
latitude: parseFloat(avgLat),
longitude: avgLong,
latitudeDelta: 0.20,
longitudeDelta: 0.20,
});

react-native-maps : How to follow user location on button press

I am using react-native-maps and it works great. But I have two problems.
I am able to follow user location automatically using the followsUserLocation but when I move the map it keeps dragging me back to the user location. How could I fix this?
I want to have refresh button, and when the user press the button, I want my map view to follow user location.
constructor() {
super();
this.state = {
followsUserLocation: true,
};
}
mapView() {
return(
<MapView style={styles.map}
showsUserLocation
followsUserLocation={this.state.followsUserLocation}
initialRegion={{
latitude: 37.523814,
longitude: 126.927494,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421}}/>
)
}
Any comments or advise would be really appreciated! Thanks in advance!
Try onUserLocationChange callback and set your region accordingly using setState
state = {
showsUserLocation: true,
followsUserLocation : true,
mapRegion: {
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
},
};
<MapView
style={{ flex: 1 }}
region={this.state.mapRegion}
//use this callback to update the regions
onUserLocationChange={event => console.log(event.nativeEvent)}
showsUserLocation={this.state.showsUserLocation}
followsUserLocation={this.state.followsUserLocation}
/>
if you are working with Reack Hook
you can create a var instead of useState.
In my case to prevent the app from crashing handled with the ternary condition.
var liveMap = {
mapRegion: {
latitude: lattitude ? lattitude : 19.88134866090193,
longitude: longitude ? longitude : 73.97658792586263,
latitudeDelta: 0.0022,
longitudeDelta: 0.0021,
},
<MapView
mapType="satellite"
style={{ height: 400, width: "100%" }}
showsUserLocation={false}
zoomEnabled={true}
zoomControlEnabled={true}
followsUserLocation={true}
// onUserLocationChange={(event) => console.log("this is event",event.nativeEvent)}
showsUserLocation={true}
followsUserLocation={true}
region={liveMap.mapRegion}
// initialRegion={{
// latitude: lattitude ? lattitude : 19.88134866090193,
// longitude: longitude ? longitude : 73.97658792586263,
// latitudeDelta: 0.0022,
// longitudeDelta: 0.0021,
// }}
>
<Marker
coordinate={{
latitude: lattitude ? lattitude : 19.88134866090193,
longitude: longitude ? longitude : 73.97658792586263,
}}
title={"JavaTpoint"}
description={"Java Training Institute"}
/>
</MapView>

Categories