8

Here is what I am thinking. I want to get user location using GPS. Instead of sending current position I want to calculate square km or meter.

----------------------------------
|                                |
|                                |
|                                | 
|                                |
|              .                 |
|              ^                 |
|      My current position       |
|                                |
|                                |
|                                |
----------------------------------

As you can see in figure above, my current position but I want to calculate the whole area around that in HTML5 or Ionic would be more preferred.

Update

enter image description here

In above image the red dot is my position and I need to get the whole area in red rectangle. Get that store that in database. I looked into the Polygon area formulas but that requires several vertices, with geolocation I only get longitude and latitude just two coordinates. How am I gonna do that using these two points?

UPDATE

I found a solution here but this solution is keep tracking user's current location and in calculateDistance function the formula uses both current location (longitude and latitude) and tracking location(longitude and latitude) i.e. Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2);

This works perfectly fine for my second scenario but first I do not want to track user's location at first. First I simple get current user location(longitude and latitude), calculate the area from that and send it to server. Now I am not sure how am I going to achieve that. Any help?

null
  • 1,112
  • 3
  • 12
  • 28
  • The thing is that the region is not a rectangle. The Earth is a sphere so you would have to either use a library or [do the math](https://stackoverflow.com/a/5820404/283863) yourself. – Derek 朕會功夫 May 25 '18 at 18:23
  • try to find out geofence I think this will be helpful. – Pritish May 31 '18 at 06:06
  • How do you want your data to be like? Do you want to calculate the square km of that area? Do you want lat-lng coordinates of the corners? Please provide your question with the desired output – Ivar Reukers May 31 '18 at 09:39
  • @Ivaro18 I do not want to draw any rectangle, I just want to get current location of user, then find its polygon/area about lets say 1000 meter square and send that as json to server where I will store. Later when user, I will track users location based on GPS and when they get into that range I will show them a message the you are in that range. Thats all. – null May 31 '18 at 09:56
  • Ok so if you have the middle point in lat-lng, can't you just calculate the lat & long values of 1km and add & substract them to create your corners of the polygon? – Ivar Reukers May 31 '18 at 10:10
  • @Ivaro18 I can but that is my weak point :( calculation. – null Jun 04 '18 at 02:03
  • What database are you using? – Kyle B Jun 05 '18 at 12:32
  • Depending on what database you are using, you might be able to send the point to the database and then use database functions to get the radius/then bounding box similar to the answer by @Makore. In this case you would have less storage, quicker inserts but slower queries. – Kyle B Jun 05 '18 at 12:42

1 Answers1

6

I've created a circle in google maps and then got his bounds, which return a square bounding boxes.

function getBounds(latLng, radius) {
  /*
  * Params:
  *     latLng: google maps LatLng object or object literal  // example: { lat: -34.397, lng: 150.644 }
  *     radius: Number(int) in Miters. For example 1000 will be 1 sq Kilometer
  * Returns:
  *     object literal in the following format:
  *         {
                northEast: {
                  lat: (float),
                  lng: (float),
                },
                southWest: {
                  lat: (float),
                  lng: (float),
                },
            }
  * */

  const circle = new google.maps.Circle({
    center: latLng,
    radius: radius
  });
  const bounds = circle.getBounds();
  const northEast = bounds.getNorthEast();
  const southWest = bounds.getSouthWest();
  return {
    northEast: {
      lat: northEast.lat(),
      lng: northEast.lng(),
    },
    southWest: {
      lat: southWest.lat(),
      lng: southWest.lng(),
    },
  };
}

I took the library to add a short snippet for you to see if this is the right answer for what you were looking for. Once you click on the map you will see a marker and the triangle around it.

Note: Please copy the code and add your google map API key. Without your API key, the map will fail to load.

let map;
let marker;
let rectangle;

function initMap() {
  const latLng = {
    lat: -34.397,
    lng: 150.644
  };
  const radius = 1000;
  map = new google.maps.Map(document.getElementById('map'), {
    center: latLng,
    zoom: 11,
  });
  google.maps.event.addListener(map, 'click', function(event) {
    const location = event.latLng;
    const bounds = getBounds(location, 1000);
    console.log(bounds);
    addRectangle(bounds);
    addMarker(location);
  });
}

function addMarker(location) {
  if (marker) {
    marker.setMap(null);
  }
  marker = new google.maps.Marker({
    position: location,
    map: map,
  });
}

function addRectangle(bounds) {
  if (rectangle) {
    rectangle.setMap(null);
  }
  rectangle = new google.maps.Rectangle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    bounds: {
      north: bounds.northEast.lat,
      south: bounds.southWest.lat,
      east: bounds.northEast.lng,
      west: bounds.southWest.lng,
    },
  });
}

function getBounds(latLng, radius) {
  /*
  * Params:
  *     latLng: google maps LatLng object or object literal  // example: { lat: -34.397, lng: 150.644 }
  *     radius: Number(int) in Miters. For example 1000 will be 1 sq Kilometer
  * Returns:
  *     object literal in the following format:
  *         {
                northEast: {
                  lat: (float),
                  lng: (float),
                },
                southWest: {
                  lat: (float),
                  lng: (float),
                },
            }
  * */

  const circle = new google.maps.Circle({
    center: latLng,
    radius: radius
  });
  const bounds = circle.getBounds();
  const northEast = bounds.getNorthEast();
  const southWest = bounds.getSouthWest();
  return {
    northEast: {
      lat: northEast.lat(),
      lng: northEast.lng(),
    },
    southWest: {
      lat: southWest.lat(),
      lng: southWest.lng(),
    },
  };
}
/* Always set the map height explicitly to define the size of the div
         * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<div id="map"></div>
Shahar
  • 2,101
  • 18
  • 23
  • 1
    Thanks for the answer, I ll give it a try but when I try to get google maps API key it asks me to provide credit card details. I cannot proceed further without details :(. Is there any other solution without Google maps API? – null Jun 05 '18 at 14:57
  • 1
    I’ll try to come out with another solution. Do you use any map engine in the client (like google maps or leaflet)? – Shahar Jun 05 '18 at 16:03
  • No I am not using any maps yet but my plan was to use google maps which is now seems to be hard because of my above reply. – null Jun 06 '18 at 02:20
  • 1
    I just gave a look to leaflet which seems good. Maybe I ll give it a try. – null Jun 06 '18 at 02:23