Store Circle Data drawn on Google Map

125 views Asked by At

I am working in a Laravel application where Polygon Coordinates drawn on Google Map store in a column with data type polygon.

enter image description here

Later below code is used to search a Coordinate inside those polygons.

$point = new Point( $request->latitude, $request->longitude );
$zone  = RestaurantZones::contains( 'coordinates', $point )->pluck( 'id' );

Now I would like to store Circle Data drawn on Google Map and search a Coordinate inside that Circle in a similar way.

1

There are 1 answers

3
Md Mainul Islam On

In a circle, you can store it by creating two fields latitude and longitude or as you have mentioned coordinates also here need to store the circle's radius to find out whether the coordinates are inside that circle or not. Let's demonstrate this.

DRAW & STORE CIRCLE'S COORDINATES AND RADIUS

let map;
let drawingManager;
let circle;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });

  drawingManager = new google.maps.drawing.DrawingManager({
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [google.maps.drawing.OverlayType.CIRCLE],
    },
    circleOptions: {
      fillColor: "#ffff00",
      fillOpacity: 0.5,
      strokeWeight: 2,
      clickable: false,
      editable: true,
      zIndex: 1,
    },
  });

  drawingManager.setMap(map);

  google.maps.event.addListener(drawingManager, "circlecomplete", function (circleObject) {
    // Remove the previous circle if it exists
    if (circle) {
      circle.setMap(null);
    }

    // Set the new circle
    circle = circleObject;

    // Log coordinates and radius
    const center = circle.getCenter();
    const radius = circle.getRadius();
    console.log("Coordinates: " + center.toUrlValue());
    console.log("Radius: " + radius + " meters");

  // Send the data to the Laravel controller using AJAX
  $.ajax({
    url: 'your-route',
    method: 'POST',
    data: {
      center: center.toUrlValue(),
      radius: radius,
    },
    success: function (response) {
      console.log(response.message);
    },
    error: function (error) {
      console.error('Error:', error);
    },
  });

  });
}

window.initMap = initMap;
#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<html>
  <head>
    <title>Drawing Tools</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

  </head>
  <body>
    <div id="map"></div>

    <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&libraries=drawing&v=weekly" async defer></script>
  </body>
</html>

when you have stored coordinates in a spatial way can use this to find out whether a coordinate is inside the circle or not

$targetPoint = new Point($latitude, $longitude);
$zone = RestaurantZones::whereRaw(
        "ST_Distance(coordinates, ?) <= radius",
        [$targetPoint]
    )->first();

    if ($zone) {
        return 'Coordinate is inside a zone';
    }

    return 'Coordinate is outside all zones';

And if coordinates are in separated in lat and lng then may you use this

public function checkCoordinateInZone($latitude, $longitude)
{
    $targetPoint = ['lat' => $latitude, 'lng' => $longitude];
    
    $zones = RestaurantZones::all();
    
    foreach ($zones as $zone) {
        $circleCenter = $zone->coordinates;
        $circleRadius = $zone->radius;
        
        $distance = $this->calculateDistance($circleCenter, $targetPoint);
        
        if ($distance <= $circleRadius) {
            return 'Coordinate is inside a zone';
        }
    }
    
    return 'Coordinate is outside all zones';
}

private function calculateDistance($point1, $point2)
{
    $lat1 = deg2rad($point1->getLat());
    $lon1 = deg2rad($point1->getLng());
    $lat2 = deg2rad($point2['lat']);
    $lon2 = deg2rad($point2['lng']);

    // Haversine formula to calculate the distance between two coordinates
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = 6371000 * $c; // Radius of Earth in meters

    return $distance;
}

May this help you Kindly read Google Map JS API to understand in a better way.