Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the bounds of a mapView

Tags:

react-native

I have an app that calls an api and returns a list of locations.

Once the data is returned, I convert the JSON to map points for annotations.

These get added to the ma with no problem.

The problem I am running into is setting the bounds of the map. I can't seem to figure it out.

The code I currently have is.

_handleResponse(response) {              
     var locations = [];
     // Loop through repsone and add items to an arra for annotations
     for (var i = 0; i < response.length; i++) {
         // Get the location
         var location = response[i];
         // Parse the co ords
         var lat = parseFloat(location.Latitude);
         var lng = parseFloat(location.Longitude);
         // Add the location to array
         locations.push({
            latitude: lat,
            longitude: lng,
            title: location.Name
         });
     }

     // This calls the map set state
     this.setState({
        annotations: locations      
     });
}

and here is my view code

<View style={styles.container}>
    <MapView
      style={styles.map}
      onRegionChangeComplete={this._onRegionChangeComplete}
      annotations={this.state.annotations}
    />
  </View>
like image 734
Wesley Skeen Avatar asked Jun 02 '15 21:06

Wesley Skeen


1 Answers

You'll want

<MapView
  ...
  region={region}
/>

where

var region = {
  latitude,
  longitude,
  latitudeDelta,
  longitudeDelta,
};

latitude and longitude are the center of the map and the deltas are the distance (in degrees) between the minimum and maximum lat/long shown. For instance, given a certain radius in miles around a point and an aspect ratio of the map view, you could calculate region as follows:

var radiusInRad = radiusInKM / earthRadiusInKM;
var longitudeDelta = rad2deg(radiusInRad / Math.cos(deg2rad(latitude)));
var latitudeDelta = aspectRatio * rad2deg(radiusInRad);

The definitions of rad2deg, deg2rad, and earthRadiusInKM are left as an exercise to the reader.

like image 93
Philipp von Weitershausen Avatar answered Sep 20 '22 05:09

Philipp von Weitershausen