Skip to main content

Command Palette

Search for a command to run...

How to auto zoom into your current location using React Native Maps

Updated
4 min read

How to auto zoom into your current location using React Native Maps

React native maps (https://github.com/react-native-community/react-native-maps ) is the go to React Native component for setting up map in your React native application.

In this article, I will show you how to get current user location and zoom into your current location when the map is loaded.

Install the component from the documentation stated in https://github.com/react-native-community/react-native-maps/blob/master/docs/installation.md

npm install react-native-maps --save</span>

Followed by :

react-native link react-native-maps</span>

Remember to re run your Android or Ios application after linking. Import the MapView component :

import MapView, { AnimatedRegion } from “react-native-maps”;</span>

Initialize the following in your state :

mapRegion will store the region of the map after the map is loaded; lastLat and lastLng will be used to store the latest lat and lng values ; initialRegion will be used to store the initial region loaded fetched from the current user location. A region of a map is defined as follows :

region: {
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421
}</span>

Latitude delta is used to control the amount of map you want to display.In short the amount of zoom. As defined in the https://developer.apple.com/documentation/mapkit/mkcoordinatespan/1452417-latitudedelta : The amount of north-to-south distance (measured in degrees) to display on the map.

Create a function to fetch the current location :

Create a function to fetch the current location :

async getCurrentLocation() {
    navigator.geolocation.getCurrentPosition(
        position => {</span> <span id="7a26" class="de im in bo io b fp is it iu iv iw iq r ir">let region = {
                latitude: parseFloat(position.coords.latitude),
                longitude: parseFloat(position.coords.longitude),
                latitudeDelta: 5,
                longitudeDelta: 5
            };
            await this.setState({
                initialRegion: region
            });
        },
        error => console.log(error),
        {
            enableHighAccuracy: true,
            timeout: 20000,
            maximumAge: 1000
        }
    );
}</span>

Call the above function in componentDidMount()

componentDidMount(){
 this.getCurrentLocation();
}</span>

Define the Map in the render function :

<MapView
            style={customMapStyle}
            region={this.state.mapRegion}
            followUserLocation={true}
            ref={ref => (this.mapView = ref)}
            zoomEnabled={true}
            showsUserLocation={true}
            onMapReady={this.goToInitialRegion.bind(this)}
            initialRegion={this.state.initialRegion}>
</MapView></span>

Define the function goToIntialRegion(). The latitude and longitude delta values are lowered to cover a smaller area of the map . animateToRegion() is a function that will animate to region passed as a parameter ( https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md ) . This will be called when the map is ready :

goToInitialLocation() {
    let initialRegion = Object.assign({}, this.state.initialRegion);
    initialRegion["latitudeDelta"] = 0.005;
    initialRegion["longitudeDelta"] = 0.005;
    this.mapView.animateToRegion(initialRegion, 2000);
  }</span>

When you re load your component , you will see that the map zooms into your current location. You can use the lastLat and lastLng values to set a custom marker on the map .

167 views
A

"This is a really practical tutorial thanks for sharing! I loved the auto-zoom feature you implemented in React Native Maps around the user’s current location. The logic with region updates and animations makes the map feel more dynamic. I’m curious have you tried combining this with marker clustering or map bounds recalc when there are multiple points? Would make a great follow-up piece! For more deep insights: https://mobisoftinfotech.com/resources/blog/app-development/react-native-maps-interactive-google-maps-tutorial"