Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How get latitudeDelta and longitudeDelta from any region? #505

Closed
cinder92 opened this issue Aug 28, 2016 · 35 comments
Closed

How get latitudeDelta and longitudeDelta from any region? #505

cinder92 opened this issue Aug 28, 2016 · 35 comments

Comments

@cinder92
Copy link

cinder92 commented Aug 28, 2016

Hello, how can i get this requirements ? because without them, my initial marker (when map runs) is in full zoom possible in map, so i need that when the map runs, it have a zoom for 10 or something, is this possible?

UPDATE:

is there any easy way to make zoom when map runs? 😕

Thanks!

@Cammoy
Copy link

Cammoy commented Aug 29, 2016

I also like to know this too, in the example the latitudeDelta has a value but I don't know how that value was calculated.

Thanks

@Exilz
Copy link

Exilz commented Aug 30, 2016

I didn't figure out how the latitudeDelta and longitudeDelta are calculated.
However, I logged the region value with the event onRegionChangeComplete to have a basic understanding of what kind of values I need to use to zoom on the markers the way I want.

If you want to zoom programmatically on anything, you can use the method animateToRegion and pass the coords, and the deltas you got from logging. You just have to find your desired "zoom" by pinching the map, and note down these values.

Here's my sample of code to center / zoom the map on one of my markers :

    onPressMarker (markerData) {
        this.setState({ openedMarker: markerData });
        this.refs.map.animateToRegion({
            latitude: parseFloat(markerData.latitude),
            longitude: parseFloat(markerData.longitude),
            latitudeDelta: 0.0043,
            longitudeDelta: 0.0034
        });
    }

This gives me exactly the zoom I want.

@uriklar
Copy link

uriklar commented Aug 30, 2016

Given an array of coordinates coords this function returns the region (lat, lng and deltas) to contain those coordinates.

export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

@Cammoy
Copy link

Cammoy commented Aug 31, 2016

HI needed to pass in an object, not an array and fix a few other variables but latitude is undefined so I am not sure why. do you have any idea? I passed both latitude and longitude.

@npomfret
Copy link

Given a point x,y your region is effectively a box around that pint, right? A GPS location has an accuracy field expressed in meters. But a region is expressed in degrees latitude and longitude, so I you need to convert meters to degrees. And because the earth is a sphere the maths (I think) is as follows:

regionFrom(lat, lon, accuracy) {
    const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
    const circumference = (40075 / 360) * 1000;

    const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
    const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

    return {
      latitude: lat,
      longitude: lon,
      latitudeDelta: Math.max(0, latDelta),
      longitudeDelta: Math.max(0, lonDelta)
    };
  }

@Larney11
Copy link

Larney11 commented Feb 3, 2017

@uriklar your formula just return 0 for longtitudeDelta and latitudeDelta.
@npomfret your formula crashes...

@npomfret
Copy link

npomfret commented Feb 8, 2017

Yeah, i thin k there's a divide by zero error that happens at 0 degrees

@npomfret
Copy link

npomfret commented Mar 9, 2017

  static regionFrom(lat, lon, accuracy) {
    const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
    const circumference = (40075 / 360) * 1000;

    const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
    const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

    return {
      latitude: lat,
      longitude: lon,
      latitudeDelta: Math.max(0, latDelta),
      longitudeDelta: Math.max(0, lonDelta)
    };
  }

@benjick
Copy link

benjick commented Apr 21, 2017

@npomfret Thank you for this, but I experience that it returns 0 quite often, do you know any way to redeem this?

@npomfret
Copy link

Returns 0? I don't understand, this function returns an object, not a number.

@cinder92
Copy link
Author

cinder92 commented May 9, 2017

thanks to all!

@cinder92 cinder92 closed this as completed May 9, 2017
@benjick
Copy link

benjick commented May 10, 2017

@cinder92 Why is there no "official" example on how to calculate delta? I'd never heard of it before this plugin, I'm sure I'm not alone

@cgrossde
Copy link

@npomfret long/lat-delta algorithm did not work for me an I have my doubts about it's correctness.
One degree of latitude in meters is independent of longitude and can be assumed a constant. One degree of longitude in meters however depends on the latitude. My code is based on the following formular:
image
(Source: http://www.movable-type.co.uk/scripts/latlong.html#destPoint)
I set the bearing to 90 degrees because I only need it to calculate the longitude delta. The latitude delta can be determined from the oneDegreeOfLatitudeInMeters constant.

This is working for me:

regionFrom(lat, lon, distance) {
        distance = distance/2
        const circumference = 40075
        const oneDegreeOfLatitudeInMeters = 111.32 * 1000
        const angularDistance = distance/circumference

        const latitudeDelta = distance / oneDegreeOfLatitudeInMeters
        const longitudeDelta = Math.abs(Math.atan2(
                Math.sin(angularDistance)*Math.cos(lat),
                Math.cos(angularDistance) - Math.sin(lat) * Math.sin(lat)))

        return result = {
            latitude: lat,
            longitude: lon,
            latitudeDelta,
            longitudeDelta,
        }
    }

@npomfret
Copy link

@cgrossde thanks for the info. Can you give an example of where mine didn't work? It looks ok in my map. I'm using it to draw a circle based on accuracy - the circle is exactly the same size as the one drawn by the native map code it you turn on user tracking.

@ShaikhKabeer
Copy link

Hi @uriklar , can you give the complete example. Here is my code.

import React from 'react';
import { StyleSheet,Text,View } from 'react-native';
import MapView from 'react-native-maps';

export default class ReactMap extends React.Component {
constructor(props){
super(props);
this.state={
markers:[{
coordinates:{
latitude: 18.5204,
longitude: 73.8567,
},
},
{
coordinates:{
latitude: 25.2744,
longitude: 133.7751,
},
},
{
coordinates:{
latitude: 37.0902,
longitude: 72.8777,

            },
        },
        {
            coordinates:{
                latitude: 46.2276,
                longitude: 2.2137,
             
            },
        }]
    }

}

  getRegionForCoordinates(points) {
    // points should be an array of { latitude: X, longitude: Y }
    let minX, maxX, minY, maxY;
    console.log("Points",points)
    // init first point
    ((point) => {
      minX = point.latitude;
      maxX = point.latitude;
      minY = point.longitude;
      maxY = point.longitude;
    })(points[0]);
  
    // calculate rect
    points.map((point) => {
      minX = Math.min(minX, point.latitude);
      maxX = Math.max(maxX, point.latitude);
      minY = Math.min(minY, point.longitude);
      maxY = Math.max(maxY, point.longitude);
    });
  
    const midX = (minX + maxX) / 2;
    const midY = (minY + maxY) / 2;
    const deltaX = (maxX - minX);
    const deltaY = (maxY - minY);
  
    return {
      latitude: midX,
      longitude: midY,
      latitudeDelta: deltaX,
      longitudeDelta: deltaY
    };
  }

render() {

    return (
       
                <MapView style={styles.map}
                region={this.state.getRegionForCoordinates(this.state.markers)}
         /*       ref={(ref)=>{this.mapRef=ref}}
                showsTraffic={true}
             //   onLayout = {(ref) => this.mapRef.fitToCoordinates(this.state.markers, { edgePadding: { top: 10, right: 10, bottom: 10, left: 10 }, animated: false })}
                onRegionChangeComplete={(region) => {
                    console.log(" region", region)
              }}    */
              >
                 
                {this.state.markers.map(marker =>   (
                    <MapView.Marker key={marker.title}
                    coordinate={marker.coordinates}
                    title={marker.title}
                    >
                    <View style={styles.radius}>
                    <View style={styles.markerStyle}/>
                    </View>
                   </MapView.Marker>
                ))}

                </MapView> 
    
    );
}

}

const styles=StyleSheet.create({
container:{
position:'absolute',
top:0,
bottom:0,
left:0,
right:0,
justifyContent:'flex-end',
alignItems:'center'
},
map:{
position:'absolute',
top:0,
bottom:0,
left:0,
right:0,
},
radius:{
height:15,
width:15,
backgroundColor:'#81BD26',
overflow:'hidden',
borderRadius:50/2,
borderWidth:1,
alignItems:'center',
justifyContent:'center'
},
markerStyle:{
height:14,
width:14,
backgroundColor:'#81BD26',
alignItems:'center',
justifyContent:'center'
}
});

@supercamilo
Copy link

supercamilo commented Dec 27, 2017

The other functions didn't work for me. @cgrossde's worked partially but I was getting some weird zoom levels when using coordinates in Bogotá, Colombia (it worked with other cities).

So I found this simplified version that seems to work everywhere:

static getDelta(lat, lon, distance): Coordinates {
       const oneDegreeOfLatitudeInMeters = 111.32 * 1000;

       const latitudeDelta =distance / oneDegreeOfLatitudeInMeters;
       const longitudeDelta = distance / (oneDegreeOfLatitudeInMeters * Math.cos(lat * (Math.PI / 180)));

       return result = {
           latitude: lat,
           longitude: lon,
           latitudeDelta,
           longitudeDelta,
       }
   }

@hugoh59
Copy link

hugoh59 commented Feb 3, 2018

@cgrossde @supercamilo what does the "distance" refer to?

@cgrossde
Copy link

cgrossde commented Feb 3, 2018

@hugoh1995 If I remember correctly it should be meters.

@theHinneh
Copy link

how do I pass the longitude and latitude received from a firebase database to be rendered in the google map with markers.
please I need help

@yeomann
Copy link

yeomann commented Jun 27, 2018

what is this stupid distance, god this delta thing is so frustrating!!

@code-by
Copy link

code-by commented Jul 17, 2018

so, having one {lag,lng} which is center of the map, how could I get (determine) any other {lat,lng} by specify x,y of View of the map?

@jnrepo
Copy link

jnrepo commented Aug 31, 2018

what is distance?

@yassernasc
Copy link

So many magic calculations..

@manojkumawat003
Copy link

manojkumawat003 commented Sep 14, 2018

Distance is 'accuracy' here.

@manojkumawat003
Copy link

manojkumawat003 commented Sep 14, 2018

Here is the solution for latitudeDelta and longitudeDelta =>

calDelta(lat,long,accuracy){
       const oneDegreeOfLatitudeInMeters = 111.32 * 1000;
       const latDelta =accuracy / oneDegreeOfLatitudeInMeters;
       const longDelta = accuracy / (oneDegreeOfLatitudeInMeters * Math.cos(lat * (Math.PI / 180)));

        this.setState({
            region:{
              latitude:lat,
              longitude:long,
              latitudeDelta:latDelta,
              longitudeDelta:longDelta,
              accuracy:accuracy,
              },
            });
    }

Here is the complete example to view marker with zoom level=>

import React, {Component} from 'react';
import {View,Text,StyleSheet,Dimensions} from 'react-native';
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps';

const {width,height} = Dimensions.get('window')

class CurrentPosition extends Component{
    constructor() {
        super();
        this.state = {
            region: {
                latitude: "",
                longitude: "",
                latitudeDelta:"",
                longitudeDelta:"",
                accuracy:"",
                }
    }

  }

    calDelta(lat,long,accuracy){
       const oneDegreeOfLatitudeInMeters = 111.32 * 1000;
       const latDelta =accuracy / oneDegreeOfLatitudeInMeters;
       const longDelta = accuracy / (oneDegreeOfLatitudeInMeters * Math.cos(lat * (Math.PI / 180)));

        this.setState({
            region:{
              latitude:lat,
              longitude:long,
              latitudeDelta:latDelta,
              longitudeDelta:longDelta,
              accuracy:accuracy,
              },
            });
    }

    componentWillMount(){

    this.watchID = navigator.geolocation.watchPosition((position)=>
           {
            const lat = position.coords.latitude;
            const long = position.coords.longitude;
            const accuracy = position.coords.accuracy;
               
            this.calDelta(lat,long,accuracy)
        },

        (error)=>{
              console.log(error.message)
        },
        {enableHighAccuracy:true,timeout:20000,maximumAge:1000,}
      )
   }

  componentWillUnmount(){
      navigator.geolocation.clearWatch(this.watchID)
  }

  marker(){
      return {
          latitude:this.state.region.latitude,
          longitude:this.state.region.longitude
      }
  }

    render(){
        console.log(this.state.region)
        return(
              <View style={styles.container}> 
                {this.state.region.latitude ? 
                <MapView 
                provider={PROVIDER_GOOGLE}
                 style={styles.map}
                 initialRegion={this.state.region}
                  >
                 <MapView.Marker
                    coordinate={this.marker()}
                    title="You"
                    description="You are here!"
                    pinColor='green'
                 />
                 
                </MapView>
                : <Text>cordinates not found</Text> }
              
               
              </View>
          
           )

    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        justifyContent:'center'
    },
    map: {
        width:width,
        height:height,
        flex: 1
        }
});

export default CurrentPosition;

I hope this will solve your problem.

@patilrevansidh
Copy link

Given an array of coordinates coords this function returns the region (lat, lng and deltas) to contain those coordinates.

export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

returning longitudeDelta:0 0

@EgorKazachenko
Copy link

If it's still actual for someone then you can find my solution here, don't know it is super stable or not , but can be useful #705 (comment)

@yasora099
Copy link

Given an array of coordinates coords this function returns the region (lat, lng and deltas) to contain those coordinates.

export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

This solution doesn't work when having location with negative longitude value and another with positive longitude value.

@nateeither
Copy link

@npomfret long/lat-delta algorithm did not work for me an I have my doubts about it's correctness.
One degree of latitude in meters is independent of longitude and can be assumed a constant. One degree of longitude in meters however depends on the latitude. My code is based on the following formular:
image
(Source: http://www.movable-type.co.uk/scripts/latlong.html#destPoint)
I set the bearing to 90 degrees because I only need it to calculate the longitude delta. The latitude delta can be determined from the oneDegreeOfLatitudeInMeters constant.

This is working for me:

regionFrom(lat, lon, distance) {
        distance = distance/2
        const circumference = 40075
        const oneDegreeOfLatitudeInMeters = 111.32 * 1000
        const angularDistance = distance/circumference

        const latitudeDelta = distance / oneDegreeOfLatitudeInMeters
        const longitudeDelta = Math.abs(Math.atan2(
                Math.sin(angularDistance)*Math.cos(lat),
                Math.cos(angularDistance) - Math.sin(lat) * Math.sin(lat)))

        return result = {
            latitude: lat,
            longitude: lon,
            latitudeDelta,
            longitudeDelta,
        }
    }

How i get "distance" ?

@karamat
Copy link

karamat commented Dec 18, 2019

Try following this, worked for me: #356 (comment)

@jereztech
Copy link

my simple solution working for me:

const getRegionFromBounds = (bounds) => { // from Directions API
    const northeastLat = bounds.northeast.lat, southwestLat = bounds.southwest.lat;
    const northeastLng = bounds.northeast.lng, southwestLng = bounds.southwest.lng;
    return {
        latitude: (northeastLat + southwestLat) / 2, // 2D middle point
        longitude: (northeastLng + southwestLng) / 2, // 2D middle point
        latitudeDelta: Math.max(northeastLat, southwestLat) - Math.min(northeastLat, southwestLat),
        longitudeDelta: (Math.max(northeastLng, southwestLng) - Math.min(northeastLng, southwestLng)) * height / width,
    };// height and width are the dimensions of the screen
}

@flora8984461
Copy link

I am not quite sure what the distance/accuracy is from in the previous answers, for me I have google location details, thus I tried with the following answer, seems to work:
https://stackoverflow.com/a/51118004/13529635

But I don't know why in the example code such as https://github.com/react-native-maps/react-native-maps/blob/master/example/examples/AnimatedMarkers.js , the const LATITUDE_DELTA is 0.0922? How is it calculated? Is it the same by details.geometry.viewport.northeast.lat - details.geometry.viewport.southwest.lat?

@calinbuzatu
Copy link

calinbuzatu commented Nov 5, 2021

import { getCenterOfBounds, getBounds } from 'geolib';

const polygonCoordinates = [{"latitude":44.28669,"longitude":28.617627},{"latitude":44.217834,"longitude":28.623731},{"latitude":44.239153,"longitude":28.589399},{"latitude":44.228768,"longitude":28.569562},{"latitude":44.186493,"longitude":28.599699},{"latitude":44.172266,"longitude":28.593594},{"latitude":44.167341,"longitude":28.547823},{"latitude":44.153657,"longitude":28.554689},{"latitude":44.153657,"longitude":28.600461},{"latitude":44.142709,"longitude":28.615725},{"latitude":44.119161,"longitude":28.608858},{"latitude":44.110948,"longitude":28.616487},{"latitude":44.084976,"longitude":28.642195},{"latitude":44.088813,"longitude":28.664319},{"latitude":44.127708,"longitude":28.66585},{"latitude":44.147966,"longitude":28.664319},{"latitude":44.174783,"longitude":28.662794},{"latitude":44.211982,"longitude":28.649062},{"latitude":44.28669,"longitude":28.617627}];

// Polygon calculations
const center = getCenterOfBounds(polygonCoordinates);
const bounds = getBounds(polygonCoordinates);

// Map size
const { width, height: sHeight } = Dimensions.get('screen');
const height = sHeight / 3;
const aspectRatio = width / height;

// Delta calculations
const zoomOutValue = 0.8;
const deltaMultiplier = (maxCoord, minCoord) => (maxCoord - minCoord) * aspectRatio * zoomOutValue;
const latitudeDelta = deltaMultiplier(bounds.maxLat, bounds.minLat);
const longitudeDelta = deltaMultiplier(bounds.maxLng, bounds.minLng);

const initialRegion = {
  ...center,
  latitudeDelta,
  longitudeDelta,
};

return (
  <MapView
    style={{ width, height }}
    initialRegion={initialRegion}
  >
    <Polygon
      coordinates={polygonCoordinates}
      fillColor="#ff000052"
      strokeColor="red"
      strokeWidth={2}
    />
  </MapView>
);

@findhumane
Copy link
Contributor

findhumane commented Dec 25, 2022

I created the following based on the mercator math in https://github.com/tuupola/php_google_maps

The key function is mercatorDegreeDeltas(latitude, longitude, width, height, zoom) which returns { latitudeDelta, longitudeDelta } for the specified latitude/longitude center point, map dimensions, and zoom level (1-20).

import React from 'react';
import { useWindowDimensions } from 'react-native';
import MapView from 'react-native-maps';
import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
import { useHeaderHeight } from '@react-navigation/elements';

const MERCATOR_OFFSET = Math.pow(2, 28);
const MERCATOR_RADIUS = MERCATOR_OFFSET / Math.PI;

function mercatorLatitudeToY(latitude) {
  return Math.round(
    MERCATOR_OFFSET - 
    (
      (
        MERCATOR_RADIUS *
          Math.log(
            (1 + Math.sin(latitude * (Math.PI / 180))) /
            (1 - Math.sin(latitude * (Math.PI / 180)))
          )
      ) / 2
    )
  );
}

function mercatorLongitudeToX(longitude) {
  return Math.round(
    MERCATOR_OFFSET +
      (
        (
          (MERCATOR_RADIUS * longitude) * Math.PI
        ) / 180
      )
  );
}

function mercatorXToLongitude(x) {
  return (
    (
      (x - MERCATOR_OFFSET) / MERCATOR_RADIUS
    ) * 180
  ) / Math.PI;
}

function mercatorYToLatitude(y) {
  return (
    (
      (
        Math.PI / 2
      ) -
        (2 * Math.atan(
              Math.exp(
                (
                  y - MERCATOR_OFFSET
                ) / MERCATOR_RADIUS
              )
            )
        )
    ) * 180
  ) / Math.PI;
}

function mercatorAdjustLatitudeByOffsetAndZoom(latitude, offset, zoom) {
  return mercatorYToLatitude(mercatorLatitudeToY(latitude) + (offset << (21 - zoom)));
}

function mercatorAdjustLongitudeByOffsetAndZoom(longitude, offset, zoom) {
  return mercatorXToLongitude(mercatorLongitudeToX(longitude) + (offset << (21 - zoom)));
}

function mercatorDegreeDeltas(latitude, longitude, width, height, zoom) {

  if (!zoom) {
    zoom = 20;
  }

  const deltaX = width / 2;
  const deltaY = height / 2;

  const northLatitude = mercatorAdjustLatitudeByOffsetAndZoom(latitude, deltaY * -1, zoom);
  const westLongitude = mercatorAdjustLongitudeByOffsetAndZoom(longitude, deltaX * -1, zoom);
  const southLatitude = mercatorAdjustLatitudeByOffsetAndZoom(latitude, deltaY, zoom);
  const eastLongitude = mercatorAdjustLongitudeByOffsetAndZoom(longitude, deltaY, zoom);

  const latitudeDelta = Math.abs(northLatitude - southLatitude);
  const longitudeDelta = Math.abs(eastLongitude - westLongitude);

  return { latitudeDelta, longitudeDelta };
}

// Somewhat arbitrarily, Riverside Park, Independence, KS 67301
const CENTER_UNITED_STATES = {
  latitude: 37.24435373025407,
  longitude: -95.70234410503208,
};

export default function MapViewWrapper() {
  const { width, height } = useWindowDimensions();
  const tabBarHeight = useBottomTabBarHeight();
  const headerHeight = useHeaderHeight();
  const initialRegion = React.useRef(null);
  const availableHeight = height - tabBarHeight - headerHeight;

  // Only calculate initial region once
  if (!initialRegion.current) {
    const { latitudeDelta, longitudeDelta } = mercatorDegreeDeltas(
      CENTER_UNITED_STATES.latitude,
      CENTER_UNITED_STATES.longitude,
      width,
      availableHeight,
      4,
    );
    
    initialRegion.current = {
      latitude: CENTER_UNITED_STATES.latitude,
      longitude: CENTER_UNITED_STATES.longitude,
      latitudeDelta: latitudeDelta,
      longitudeDelta: longitudeDelta,
    };
  }

  return (
    <MapView
      initialRegion={initialRegion.current}
      style={{ width: width, height: availableHeight }}
    />
  );
}

There is at least one issue: if you change the zoom from 4 to 3, it isn't centered properly, but larger zoom values work. I don't need the lower zoom values right now, so I haven't investigated the math any further (maybe some sort of overflow?).

@VaporFoxLash
Copy link

  static regionFrom(lat, lon, accuracy) {
    const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
    const circumference = (40075 / 360) * 1000;

    const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
    const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

    return {
      latitude: lat,
      longitude: lon,
      latitudeDelta: Math.max(0, latDelta),
      longitudeDelta: Math.max(0, lonDelta)
    };
  }

This worked for me. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests