<?php
    session_start();
    include ('includes/db1config.php');
    include ('../includes/mysql_connect.php');
	//API key 
	$key = "AIzaSyBc_JFooooqWsSyeQJ-EQk3ncXLSdKu5LU";

    if (!isset($_GET['zone']) || empty($_GET['zone'])) {
        die('No zone number specified.');
    }

    $zoneId = trim($_GET['zone']);

    // Get zone coordinates
    $sql = "SELECT *
            FROM delivery_zones
            WHERE recordkey = '".mysql_real_escape_string($zoneId)."'";
    $result = mysql_query($sql) or die(mysql_error());

    if (mysql_num_rows($result) < 1) {
        die('Zone not found.');
    }

    $zone = mysql_fetch_assoc($result);

    // Parse coordinates
    $coordinates = [];
    $zoneCoordinates = explode(' ', $zone['coordinates']);
    foreach ($zoneCoordinates as $zoneCoordinate) {
        list($long, $lat) = explode(',', $zoneCoordinate);
        $coordinates[] = $lat.','.$long;
    }

    $firstCoordinate = reset($coordinates);
?>
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple Polygon</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0;
        padding: 0;
      }

    </style>
    <script src="https://maps.googleapis.com/maps/api/js?key=<?php echo $key;?>&v=3.exp&signed_in=true"></script>
    <script>
// This example creates a simple polygon representing the Bermuda Triangle.

function initialize() {
    if (!google.maps.Polygon.prototype.getBounds) {
 
google.maps.Polygon.prototype.getBounds=function(){
    var bounds = new google.maps.LatLngBounds()
    this.getPath().forEach(function(element,index){bounds.extend(element)})
    return bounds
}
 
}

  var mapOptions = {
    zoom: 12,
    center: new google.maps.LatLng(<?php echo $firstCoordinate; ?>),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var polygon;

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Define the LatLng coordinates for the polygon's path.
  var polygonCoords = [
    <?php foreach ($coordinates as $coordinate) : ?>
    new google.maps.LatLng(<?php echo $coordinate; ?>),
    <?php endforeach; ?>
  ];

  // Construct the polygon.
  polygon = new google.maps.Polygon({
    paths: polygonCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  map.fitBounds(polygon.getBounds());

  polygon.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>