Locations Dashboard

Manage Locations Widget Code

Create a dashboard widget

<div class="container-fluid h-100 p-0">
  
        <div class="mapdata" id="mapGeo" style="height:100%;width:100%;position:relative">
            
        </div>
        <button type="button" class="btn btn-warning btn-sm" style="float:right;margin-top:-5px;position:absolute;top:25px;right:10px"  onclick="openModal(1)"><i class="fa fa-plus"></i> Create</button>
        <div class="transpernetProcessing">
              <div class="loader">
                <p style="font-size: 21px;"><i class="fa fa-spinner fa-spin"></i></p>
                <p class="p-2" style="font-size: 14px;font-weight: 600;"> Processing...</p>
                <p class="loader__label">Please wait,it take a moments</p>
              </div>
            </div>
        <div id="snackbar"><i class="fa fa-exclamation-triangle"></i> Geofence Name is Required</div>
       <div>
            <div class="map-top-tools d-none">
                <div class="map-tools panel-heading" style="background-color: #56AF50">Tools</div>
                <div class="g-list-tools">
                    <button class="min-tool-btn btn" id="DEFAULT" onclick="mapTools('DEFAULT')" title="Move"> <i class="icon-hand-paper-o" aria-hidden="true"></i> </button>
                    <br>
                    <button class="min-tool-btn btn" onclick="resetAll()" title="Reset Map"> <i class="icon-refresh" aria-hidden="true"></i> </button>
                    <br>
                    <button class="min-tool-btn btn" id="POLYGON" onclick="mapTools('POLYGON')" title="Polygon">
                        <img src="images/map/polygon.png">
                    </button>
                    <br>
                    <button class="min-tool-btn btn" id="LINESTRING" onclick="mapTools('LINESTRING')" title="Polyline"> <img src="images/map/polyline.png"> </button>
                    <br>
                    <button class="min-tool-btn btn" id="CIRCLE" onclick="mapTools('CIRCLE')" title="Circle"> <i class="icon-circle-o" aria-hidden="true"></i> </button>
                    <br>
                    <button class="min-tool-btn btn" id="POINT" onclick="mapTools('POINT')" title="Marker / Point"> <i class="icon-map-marker" aria-hidden="true"></i> </button>
                    <br>
                    
                </div>
            </div>
        </div>
      <div class="tableContainer col-lg-7 col-md-8 col-sm-12 col-xs-12 p-0">
        <div class="card-header GListheader accordion-toggle"><span>Manage - </span><span>Total Geofence (<strong class="totalGeo"></strong>)</span></div>
        <div class="row no-gutters tbl-style mt-3">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 overflow-mbl pr-0">
                <table id="geofenceTable" class="table  no-wrap table no-wrap no-footer dataTable d-table" cellspacing="0" width="100%"></table>
            </div>
        </div>
    </div>
    <div class="row geofenceAdd d-none">
        <div class="col">
            <form action="javascript:void(0)" id="geoCreate">
                <div class="row geoCreateHeader">
                    <button class="btn btn-sm btn-default" type="button" onclick="closeModal()"><i class="fa fa-angle-left"></i> Back</button>
                    <span class="actionHead">Create Geofence</span>
                </div>
                <div class="row" style="padding-top: 70px;">
                    <div class="col-md-12">
                        <label>Search Location</label>
                        <div class="form-group" style="position: relative">
                            <input id="locationSearch" class="form-control input-sm pac-target-input" placeholder="Seach Location"  type="text" autocomplete="off">
                        </div>
                    </div>                
                </div>
                <div class="row" style="margin-top: 1px;">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Geofence Name <span class="text-danger">*</span></label>
                            <input type="text" maxlength="50" class="input-sm form-control" id="geofencename" required/>
                        </div>
                    </div>
                </div>               
                <div class="row"><div class="col-md-6">
                    <div class="form-group">
                        <label>Geofence Type <span class="text-danger">*</span></label>
                        <select class="input-sm form-control" id="geoType" onchange="toggleGeoType()" required>
                            <option value="POINT" onclick="mapTools('POINT')">POINT</option>
                            <option value="CIRCLE" onclick="mapTools('CIRCLE')">CIRCLE</option>
                            <!--<option value="ENVELOPE">ENVELOPE</option>-->
                            <option value="LINESTRING" onclick="mapTools('LINESTRING')">LINESTRING</option>
                            <option value="POLYGON" onclick="mapTools('POLYGON')">POLYGON</option>
                            <!--<option value="MULTIPOINT">MULTIPOINT</option>-->
                            <!--<option value="MULTILINESTRING">MULTILINESTRING</option>-->
                            <!--<option value="MULTIPOLYGON">MULTIPOLYGON</option>-->
                            <!--<option value="GEOMETRYCOLLECTION">GEOMETRYCOLLECTION</option>-->
                        </select>
                    </div>
                </div></div>
                <div class="row" style="margin-top: 1px;">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Label <span class="text-danger">*</span></label>
                            <input type="text" maxlength="50" class="input-sm form-control" id="labelGeo" required/>
                        </div>
                    </div>
                </div>         
                <div class="row geoBody" style="background-color: #eee9;padding: 20px 20px;">
               <div class="coordinates">
                    <!--POINT-->
                    <div id="GEOTYPE_POINT" class="geo-type-fields" style="display: none;">
                        <div class="form-group">
                            <label for="name">Latitude <sup>*</sup></label>
                            <input type="text" class="form-control geo-input" placeholder="Latitude" name="lat" id="pointLat">
                        </div>
                        <div class="form-group">
                            <label for="name">Longitude <sup>*</sup></label>
                            <input type="text" class="form-control geo-input" placeholder="Longitude" name="lng" id="pointLong">
                        </div>
                    </div>
                    <!--CIRCLE-->
                    <div style="display: none;" id="GEOTYPE_CIRCLE" class="geo-type-fields">
                        <p class="sm-title">Circle Center  <i style="font-size: 11px;">(Lat,Long)</i></p>
                        <div class="form-group">
                            <label for="name">Latitude <sup>*</sup></label>
                            <input type="text" class="form-control geo-input" placeholder="Latitude" name="lat" id="bskpLat">
                        </div>
                        <div class="form-group">
                            <label for="name">Longitude <sup>*</sup></label>
                            <input type="text" class="form-control geo-input" placeholder="Longitude" name="lat" id="bskpLong">
                        </div>
                        <div class="form-group">
                            <label for="name">Circle Radius <sup>*</sup> <i style="font-size: 11px;">(meter)</i></label>
                            <input type="text" class="form-control geo-input" placeholder="Radius" name="radius" id="bskpCircleRadius">
                        </div>
                    </div>
                    <!--LINESTRING-->
                    <div style="display: none;" id="GEOTYPE_LINESTRING" class="geo-type-fields">
                        <p class="sm-title">Linestring Coordinates <i style="font-size: 11px;">(Eg: <code>[[-77.03, 38.89], [-77.05, 38.88]]</code>)</i></p>
                        <div class="form-group">
                            <label for="name">Coordinates <sup>*</sup> <i style="font-size: 11px;">(meter)</i></label>
                            <textarea type="text" class="form-control geo-input" placeholder="Enter Coordinates" name="coordinatesGroup" id="linestringCoordinates"></textarea>
                        </div>
                    </div>
                    <!--POLYGON-->
                    <div id="GEOTYPE_POLYGON" class="geo-type-fields">
                        <div class="form-group">
                            <label for="name">Polygon Coordinates <sup>*</sup> <i style="font-size: 11px;">(Eg: <code>[[-77.03, 38.89], [-77.05, 38.88],...,[-77.03, 38.89]]</code>)</i></label>
                            <textarea type="text" class="form-control geo-input" placeholder="Enter Coordinates" name="coordinatesGroup" id="polygonCoordinates"></textarea>
                        </div>
                    </div>
                </div>    </div>          
                <div class="row" style="margin-top: 1px;">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="description">Description </label>
                        <textarea type="text" class="form-control geo-input" placeholder="Description" name="description" id="description"></textarea>
                        </div>
                    </div>
                </div>      
                <div class="row">
                    <div class="col-md-12" style="text-align: center;margin-top: 10px;">
                        <button class="btn btn-sm btn-outline-dark btnSubmit" type="submit" id="geoCreateSubmit" onclick="upsertEntityGeofence()">Create Geofence</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    </div>
</div>
var title = 'Geofence';
var lat = 51.507351;
var lng = -0.127758;
var zoom = 2;
var geoStatus = "label";
var drawingManager;
var geofenceTable = null;
var current_geofence_id = "";
var geofence_list = [];


var geoMap ;
var geodata  = [];
var geofenceObj = {
        "group": "GEOFENCE",
        "name": "",
        "geoType": "POINT",
        "label": "",
        "description": "",
        "coordinates": "",
        "radius": 50,
        "geometries": "",
        "locationSearch": "",
        "coordinatesGroup": "",
        "lat": "",
        "lng": ""
    };
var markersGroup  = [];
var circlesGroup  = [];
var polygonGroup  = [];
var polylineGroup  = [];

var newGeoMarker ;
var newGeoCircle ;
var newGeoPolygon ;
var newGeoPolyline ;
var Google="google.map.key";

var all_overlays = []

$(document).ready(function () {
    //To start realtime time update
   startLiveUpdate();
   GetGoogleApiKey()
});
 // for realtime update, call the initial method inside this function too
function liveUpdate(){ 
  GetGoogleApiKey()
}
function initialize(){
    loadGeoList();
    geofenceInit()
    $("#geoType").on('change',function (e) {
       mapTools(e.target.value);
    });
    $("#geofenceCreateType option[value=" + $("#geoCreateType").val()+"]").attr("selected","selected") ;

}
function searchByQuery(data, cbk) {
       	$.ajax({
        	url: API_BASE_PATH + "/elastic/search/query/" + API_TOKEN,
            data: JSON.stringify(data),
             contentType: "application/json",
            type: 'POST',
            success: function (data) {
             //called when successful
               cbk(true, data);
            },
        error: function (e) {
         //called when there is an error
          cbk(false, e);
        }
	});
}
// searchqueryformatter----------
function searchQueryFormatter(data) {

      var resultObj = {
         total: 0,
         data: {},
         aggregations: {}
        };

      if (data.httpCode === 200) {
      var arrayData = JSON.parse(data.result);
      var totalRecords = arrayData.hits.total.value;
      var records = arrayData.hits.hits;
      var aggregations = arrayData.aggregations ? arrayData.aggregations : {};
      for (var i = 0; i < records.length; i++) {
      records[i]['_source']['_id'] = records[i]['_id'];
      }

       resultObj = {
         "total": totalRecords,
          "data": {
              "recordsTotal": totalRecords,
              "recordsFiltered": totalRecords,
               "data": _.pluck(records, '_source')
            },
            aggregations: aggregations
         };

        return resultObj;
  
    } else {
 
   return resultObj;
   }
}
// GEOFENCE LIST
function loadGeoList(){
    
    const self = this;
    if (geofenceTable) {
        geofenceTable.destroy();
        $("#geofenceTable").html("");
    }

    var fields = [

        {
            mData: 'name',
            sTitle: 'Name',
            sWidth:'20%',
            orderable: false,
            mRender: function(data, type, row) {
                return '<span title="'+row['name']+'" onclick="singleGeoSnapshot(\'' + encodeURIComponent(JSON.stringify(row)) + '\')" style="cursor: pointer;">'+data  +
                    '<i class="fa fa-eye ml-2" style="font-size:11px;color:#666"></i></span><p  style="font-size:11px;color:#666;margin-top:4px;"><small>'+row['geoType']  +'</small></p>'
            }
        },

       
        {
            mData: 'label',
            sTitle: 'Label',
            sWidth:'20%',
            orderable: false,
            mRender: function(data, type, row) {
                return data ? data : '-';
            }
        },

        {
            mData: 'createdAt',
            sTitle: 'Created At',
            sWidth:'30%',
            mRender: function(data, type, row) {
                var str = ''; //row['updatedbyname'] ? '<br><small>by, ' + row['updatedbyname'] + '</small>' : ''

                return data ? moment(data).format('MM/DD/YYYY hh:mm a') + str : '-';
            }
        },
        {
            mData: 'action',
            sTitle: 'Action',
            orderable: false,
            sWidth: '10%',
            mRender: function(data, type, row) {


                var str = `
                <button class="btn btn-xs btn-default"title='Edit' onclick="openModal(2,'` + row["_id"] + `')"><i class="fa fa-pencil"></i> </button>
            <button class="btn btn-xs btn-default"title='Delete' onclick="proceedDelete('` + row["name"] + `','` + row["_id"] + `')"><i class="fa fa-trash"></i> </button>
             
            
					`
                return str;

            }
        }

    ];


    var domainKeyJson = { "match": { "domainKey": DOMAIN_KEY } };

    var queryParams = {
        query: {
            "bool": {
                "must": [],
            }
        },
        sort: [],
    };

    var tableOption = {

        "language": {
            searchPlaceholder: "Search by Name / Type",
            // "search": '<i class="fa fa-search"></i>',
            "processing": '<i class="fa fa-spinner fa-spin"></i> Processing',
            "sLengthMenu": "Show _MENU_ records",
            "info": "Showing _START_ to _END_ of _TOTAL_ records",
            "infoFiltered": ""

        },
        responsive: true,
        paging: true,
        scrollY: 320,
        searching: true,
        aaSorting: [
            [2, 'desc']
        ],
        "ordering": true,
        iDisplayLength: 5,
        lengthMenu: [
            [5, 10, 50, 100],
            [5, 10, 50, 100]
        ],
        aoColumns: fields,
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": API_BASE_PATH + '/elastic/search/query/' + API_TOKEN ,

        "fnServerData": function(sSource, aoData, fnCallback, oSettings) {


            var keyName = fields[oSettings.aaSorting[0][0]]

            var sortingJson = {};
            sortingJson[keyName['mData']] = { "order": oSettings.aaSorting[0][1] };
            queryParams.sort = [sortingJson];
            queryParams.query['bool']['must'] = [];
            queryParams.query["bool"]["should"] = [];
            delete queryParams.query["bool"]["minimum_should_match"];
            queryParams['size'] = oSettings._iDisplayLength;
            queryParams['from'] = oSettings._iDisplayStart;

            var searchText = oSettings.oPreviousSearch.sSearch;

            if (searchText) {
                queryParams.query["bool"]["should"].push({
                    wildcard: { name: "*" + searchText + "*" },
                });
                queryParams.query["bool"]["should"].push({
                    wildcard: { name: "*" + searchText.toLowerCase() + "*" },
                });
                queryParams.query["bool"]["should"].push({
                    wildcard: { name: "*" + searchText.toUpperCase() + "*" },
                });

                queryParams.query["bool"]["minimum_should_match"] = 1;
                queryParams.query["bool"]["should"].push({
                    match_phrase: {
                        "name": "*" + searchText.trim() + "*",
                    },
                });
                queryParams.query["bool"]["should"].push({
                    match_phrase_prefix: {
                        "name": {
                            query: "*" + searchText.trim() + "*",
                        },
                    },
                });
                queryParams.query["bool"]["should"].push({
                    wildcard: { geoType: "*" + searchText + "*" },
                });
                queryParams.query["bool"]["should"].push({
                    wildcard: { geoType: "*" + searchText.toLowerCase() + "*" },
                });
                queryParams.query["bool"]["should"].push({
                    wildcard: { geoType: "*" + searchText.toUpperCase() + "*" },
                });

                queryParams.query["bool"]["minimum_should_match"] = 1;
                queryParams.query["bool"]["should"].push({
                    match_phrase: {
                        "geoType.text": "*" + searchText + "*",
                    },
                });
                queryParams.query["bool"]["should"].push({
                    match_phrase_prefix: {
                        "geoType.text": {
                            query: "*" + searchText + "*",
                        },
                    },
                });

            }
            queryParams.query['bool']['must'].push(domainKeyJson);

            var ajaxObj = {
                "method": "GET",
                "extraPath": "",
                "query": JSON.stringify(queryParams),
                "params": [],
                "type":"GEOFENCE"
            };



            oSettings.jqXHR = $.ajax({
                "dataType": 'json',
                "contentType": 'application/json',
                "type": "POST",
                "url": sSource,
                "data": JSON.stringify(ajaxObj),
                success: function (data) {

                    var fullObj = searchQueryFormatter(data);
                    var resultData = fullObj.data;
                    geofence_list =resultData.data;
                    geodata = resultData.data;
                    $('.totalGeo').html(fullObj.total)
                    geofenceMapManagement();
                    google.maps.event.trigger(geoMap, 'resize'); // Refresh Map
                    restoreRecord();

                    $("#entityGeoCount").html(fullObj.total);

                    resultData['draw'] = oSettings.iDraw;

                    fnCallback(resultData);
                }
            });
        }

    };

    geofenceTable = $("#geofenceTable").DataTable(tableOption);

    // geofenceTable.on( 'draw', function () {
    //     var body = $( geofenceTable.table().body() );

    //     body.unhighlight();
    //     body.highlight( geofenceTable.search() );
    // } );
}
// GEOFENCE MAP INI
function geofenceInit(){
    $('.transpernetProcessing').addClass('hide')
    var mapDiv = document.getElementById('mapGeo');
    // var geocoder = new google.maps.Geocoder();
    geoMap = new google.maps.Map(mapDiv, {
        center: new google.maps.LatLng(lat, lng),
        zoom: zoom,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    google.maps.event.addListener(geoMap, 'click', function(e) {});
    
    searchLocationAPI();
    googleMapDrawingTool();
    $(".map-top-tools").addClass('d-none').removeClass('d-block');
    drawingManager.setOptions({
        drawingControl: false
    });
   google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
    all_overlays.push(e);
    if (e.type != google.maps.drawing.OverlayType.MARKER) {
      // Switch back to non-drawing mode after drawing a shape.
      drawingManager.setDrawingMode(null);

      // Add an event listener that selects the newly-drawn shape when the user
      // mouses down on it.
    //   var newShape = e.overlay;
    //   newShape.type = e.type;
    //   google.maps.event.addListener(newShape, 'click', function() {
    //     setSelection(newShape);
    //   });
    //   setSelection(newShape);
    }
  });
}
function geofenceMapManagement(){
    if(markersGroup.length > 0){
        _.each(markersGroup,function(marker,i){
            marker.setMap(null);
        });
    }

    if(circlesGroup.length > 0){
        _.each(circlesGroup,function(circle,i){
            circle.setMap(null);
        });
    }

    if(polygonGroup.length > 0){
        _.each(polygonGroup,function(polygon,i){
            polygon.setMap(null);
        });
    }

    if(polylineGroup.length > 0){
        _.each(polylineGroup,function(polyline,i){
            polyline.setMap(null);
        });
    }


    var centersArray = [];
    markersGroup = [];
    resetAll();

    _.each(geodata,function (val,i) {

        val.geoType = val.geoType.toUpperCase();

        if(val.geoType){

            if(val.geoType == "POINT") {

                val.location["coordinates"] = val.location.coordinates;
                val["description"] = val.description;

                var center= {
                    lat : val.location.coordinates[0],
                    lng : val.location.coordinates[1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div><b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/pin.png' > POINT</p>"+
                    "</div>" +
                    "</div>"
                });

                // Create marker
                var marker = new google.maps.Marker({
                    map: geoMap,
                    position: new google.maps.LatLng(center),
                    title: val.name,
                    animation: google.maps.Animation.DROP,
                    icon:icon
                });
                marker.addListener('click', function() {
                    infowindow.open(geoMap, marker);
                    geoMap.panTo(center);
                    geoMap.setZoom(17);
                });

                // infowindow.open(geoMap, marker);

            }
            else if(val.geoType == "CIRCLE"){  //DRAW CIRCLE

                val.location["coordinates"] = val.location.coordinates;

                var center= {
                    lat : val.location.coordinates[0],
                    lng : val.location.coordinates[1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div><b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/oval.png' > CIRCLE</p>"+
                    "</div>" +
                    "</div>"
                });
                // Create marker
                var marker = new google.maps.Marker({
                    map: geoMap,
                    position: new google.maps.LatLng(center),
                    title: val.name,
                    animation: google.maps.Animation.DROP,
                    icon:icon
                });
                marker.addListener('click', function() {
                    infowindow.open(geoMap, marker);
                    geoMap.panTo(center);
                    geoMap.setZoom(17);
                });
                // infowindow.open(geoMap, marker);
                var geofenceCircle = new google.maps.Circle({
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#FF0000',
                    fillOpacity: 0.35,
                    map: geoMap,
                    center: center,
                    radius: Number(val.location.radius)
                });

                circlesGroup.push(geofenceCircle);

            }
            else if(val.geoType == "LINESTRING"){  //DRAW LINESTRING


                val.location["coordinates"] = val.location.coordinates;

                var center= {
                    lat : val.location.coordinates[0][0],
                    lng : val.location.coordinates[0][1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div>" +
                    "<b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/polyline.png' > LINESTRING</p>"+
                    "</div>" +
                    "</div>"
                });

                // Create marker
                var marker = new google.maps.Marker({
                    map: geoMap,
                    position: new google.maps.LatLng(center),
                    title: val.name,
                    animation: google.maps.Animation.DROP,
                    icon:icon
                });
                marker.addListener('click', function() {
                    infowindow.open(geoMap, marker);
                    geoMap.panTo(center);
                    geoMap.setZoom(17);
                });
                // infowindow.open(geoMap, marker);

                var lineCoords = [];
                _.each(val.location.coordinates,function(val,i){

                    var oneCoord = {};
                    oneCoord["lat"] = val[0];
                    oneCoord["lng"] = val[1];
                    lineCoords.push(oneCoord);
                });

                var geoLineString = new google.maps.Polyline({
                    path: lineCoords,
                    strokeColor: "#FF0000",
                    strokeOpacity: 1.0,
                    strokeWeight: 2
                });
                geoLineString.setMap(geoMap);
                polylineGroup.push(geoLineString);

            }
            else if(val.geoType == "POLYGON"){  //DRAW POLYGON

                val.location["coordinates"] = val.location.coordinates;

                var center= {
                    lat : val.location.coordinates[0][0][0],
                    lng : val.location.coordinates[0][0][1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div><b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/polygon.png' > POLYGON</p>"+
                    "</div>" +
                    "</div>"
                });

                // Create marker
                var marker = new google.maps.Marker({
                    map: geoMap,
                    position: new google.maps.LatLng(center),
                    title: val.name,
                    animation: google.maps.Animation.DROP,
                    icon:icon
                });
                marker.addListener('click', function() {
                    infowindow.open(geoMap, marker);
                    geoMap.panTo(center);
                    geoMap.setZoom(17);
                });
                // infowindow.open(geoMap, marker);
                

                var polyCoords = [];
                _.each(val.location.coordinates[0],function(val,i){

                    var oneCoord = {};
                    oneCoord["lat"] = val[0];
                    oneCoord["lng"] = val[1];
                    polyCoords.push(oneCoord);
                });

                // Construct the polygon.
                var geoPoly = new google.maps.Polygon({
                    paths: polyCoords,
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#FF0000',
                    fillOpacity: 0.35
                });
                geoPoly.setMap(geoMap);
                polygonGroup.push(geoPoly);
            }
            centersArray.push(center);

            markersGroup.push(marker);

        }
    });

    
}
function searchLocationAPI() {

    var map = geoMap;
    var input = document.getElementById('locationSearch');

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    autocomplete.addListener('place_changed', function() {
         var place = autocomplete.getPlace();

        geofenceObj.autocomplete = autocomplete;
        geofenceObj['lat'] = place.geometry.location.lat();
        geofenceObj['lng'] = place.geometry.location.lng();
        geofenceObj['geoType'] = $("#geoType").val() ? $("#geoType").val() : "POINT";

        mapPreview();
    });
}
function mapPreview(){
    var place = geofenceObj.autocomplete.getPlace();
     var geofence = geofenceObj.autocomplete.getPlace();
     var map = geoMap;
     // var geofenceObj = geofenceObj;

    google.maps.event.trigger(map, 'resize'); // Refresh Map

    var icon = {
        url: "images/map/marker_red.png", // url
        scaledSize: new google.maps.Size(32, 32) // scaled size
    };

    if (!place.geometry) {
        return;
    }

    if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
    } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);
    }

    geofence.latlng = place.geometry.location;
    geofence.address = place.formatted_address;

    var val = {
        title : geofenceObj.name,
        description : geofenceObj.description,
        location : geofence.address,
        lat : geofence.latlng.lat(),
        lng : geofence.latlng.lng(),
        strokeColor: "#08c",
        radius: geofence.radius,
        fillColor: "#08c"
    };

    var center= {
        lat : val.lat,
        lng : val.lng
    };


    newGeoMarker = new google.maps.Marker({
        map: geoMap,
        position: new google.maps.LatLng(center),
        title: geofenceObj.name,
        animation: google.maps.Animation.DROP,
        draggable: true,
        icon : icon
    });

    var html =
        '<b>'+val.location ? val.location : ''+'</b> <br>' +
        '<b>'+val.location ? val.location : ''+'</b>';

    var infowindow = new google.maps.InfoWindow({
        content:html

    });
    

    // infowindow.open(map, newGeoMarker);
    newGeoMarker.addListener('click', function() {
        infowindow.open(map, newGeoMarker);
        map.panTo(center);
        map.setZoom(17);
    });

    infowindow.open(map, newGeoMarker);

    if(geofenceObj.geoType == "POINT"){

        $("#pointLat").val(center.lat);
        $("#pointLong").val(center.lng);

    }else if(geofenceObj.geoType == "CIRCLE"){
        $("#bskpLat").val(center.lat);
        $("#bskpLong").val(center.lng);
        $("#bskpCircleRadius").val(50);

        newGeoCircle = new google.maps.Circle({
            strokeColor: '#FF0000',
            editable: true,
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            draggable: true,
            map: map,
            center: center,
            radius: geofenceObj.radius ? geofenceObj.radius : 50
            // radius: 100
        });

        newGeoCircle.bindTo('center', newGeoMarker, 'position');
        newGeoMarker._myCircle = newGeoCircle;

        //Common Circle Radius Listener
        google.maps.event.addListener(newGeoCircle, 'radius_changed', function () {
            geofenceObj.radius = newGeoCircle.getRadius();
            $("#bskpCircleRadius").val(geofenceObj.radius);
        });

        newGeoMarker.addListener('dragend', function(event){
            geofenceObj.lat = event.latLng.lat();
            geofenceObj.lng = event.latLng.lng();

            $("#bskpLat").val(geofenceObj.lat);
            $("#bskpLong").val(geofenceObj.lng);
        });

    }else if(geofenceObj.geoType == "LINESTRING"){


    }else if(geofenceObj.geoType == "POLYGON"){

    }

    // mapTools('DEFAULT');
}
function getMarkerUniqueId(lat, lng) {
    return lat + '_' + lng;
}
function googleMapDrawingTool(){

     var map = geoMap;
     var drawingStyle = {
        strokeWeight: 2,
        fillOpacity: 0.45,
        editable: true,
        draggable: true
    };

    drawingManager = new google.maps.drawing.DrawingManager({
        // drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingMode: null,
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: ['marker', 'circle', 'polygon']
        },
        markerOptions: {
            icon: 'images/map/marker_red.png',
            clickable: true,
            editable: true,
            draggable: true
        },
        circleOptions: {
            fillColor: '#FF0000',
            clickable: false,
            editable: true,
            zIndex: 1,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillOpacity: 0.35,
            draggable: true
        },
        rectangleOptions: drawingStyle,
        polygonOptions: drawingStyle
    });
    drawingManager.setMap(map);

         // var drawingManager = drawingManager;

    //Common OverlayComplete Listener
    google.maps.event.addListener(drawingManager, "overlaycomplete", function(event) {
        $("#widgetButton").click();
        overlayClickListener(event.overlay);
         var newShape = event.overlay;
        newShape.type = event.type;

        if(geofenceObj.geoType == "POINT"){  //POINT

            var centerLtlg = event.overlay.position;
            var markerId = getMarkerUniqueId(centerLtlg.lat(), centerLtlg.lng());
            var newMark = new google.maps.Marker({
                draggable: true,
                id: 'marker_' + markerId
            });
            markersGroup[markerId] = newMark;

            google.maps.event.addListener(newShape, 'rightclick', function(e) {

                var newMark2 = markersGroup[markerId];
                removeThisMarker(newMark2,markerId);
            });

            drawingManager.setDrawingMode(null);

        }else if(geofenceObj.geoType == "CIRCLE"){  //CIRCLE
             var newShape = event.overlay;
            newGeoCircle = newShape;

            var lat = newGeoCircle.getCenter().lat();
            var lng = newGeoCircle.getCenter().lng();

            geofenceObj.lat = lat;
            geofenceObj.lng = lng;
            $("#bskpLat").val(lat);
            $("#bskpLong").val(lng);
            $("#bskpCircleRadius").val(50);
             newGeoCircle.setRadius(50)
            // openCreateGeoModal();
            //Common Circle Drag Listener
            newGeoCircle.addListener('radius_changed', function(event){
               if(newGeoCircle.getRadius() >=10 && newGeoCircle.getRadius() <= 250){
                    geofenceObj.radius = newGeoCircle.getRadius();
                $("#bskpCircleRadius").val(geofenceObj.radius);
                }else{
                    newGeoCircle.setRadius(250)
                }
                
                
            });

            //Common Circle Drag Listener
            newGeoCircle.addListener('center_changed', function(event){

                var lat = newGeoCircle.getCenter().lat();
                var lng = newGeoCircle.getCenter().lng();
                geofenceObj.lat = lat;
                geofenceObj.lng = lng;
                $("#bskpLat").val(lat);
                $("#bskpLong").val(lng);
            });

            if(newGeoMarker){

                newGeoCircle.bindTo('center', newGeoMarker, 'position');
                newGeoMarker._myCircle = newGeoCircle;

                newGeoMarker.addListener('dragend', function(event){
                    geofenceObj.lat = event.latLng.lat();
                    geofenceObj.lng = event.latLng.lng();

                    $("#bskpLat").val(geofenceObj.lat);
                    $("#bskpLong").val(geofenceObj.lng);
                });

            }

            drawingManager.setDrawingMode(null)
        }
        else if(geofenceObj.geoType == "POLYGON"){ //POLYGON

            newGeoPolygon = newShape;
            var temp=[];
            _.each(event.overlay.getPath().getArray(),function(val,i){

                 var st2 = [];
                st2.push(val.lat());
                st2.push(val.lng());
                temp.push(st2);
            });

            if(!(_.isEqual(temp[0],temp[temp.length-1]))){  //Add polygon close coordinate check
                temp.push(temp[0]);
            }
            geofenceObj.coordinatesGroup = temp;
            $('#polygonCoordinates').val(JSON.stringify(temp));

            drawingManager.setDrawingMode(null)

        }
        else if(geofenceObj.geoType == "LINESTRING"){ //LINESTRING

            newGeoPolyline = newShape;

             var temp=[];
            _.each(event.overlay.getPath().getArray(),function(val,i){

                 var st2 = [];
                st2.push(val.lat());
                st2.push(val.lng());
                temp.push(st2);
            });

            geofenceObj.coordinatesGroup = temp;
            $('#linestringCoordinates').val(JSON.stringify(temp));
            drawingManager.setDrawingMode(null)

        }

        $("#geoType").val(geofenceObj.geoType);
        $(".map-top-tools .min-tool-btn").removeClass("active");
        $("#DEFAULT").addClass("active");
    });
    
    
}
function singleGeoSnapshot(obj){
    $header = $('.GListheader');
    $content = $header.next();
    $content.slideToggle(500, function () { });

    var oneGeoObj = JSON.parse(decodeURIComponent(obj));
    oneGeoObj.geoType = oneGeoObj.geoType.toUpperCase();
    var center= {};

    if(oneGeoObj.geoType == "POINT"){

        center["lat"] = oneGeoObj.location.coordinates[0];
        center["lng"] = oneGeoObj.location.coordinates[1];

    }else if(oneGeoObj.geoType == "CIRCLE"){

        center["lat"] = oneGeoObj.location.coordinates[0];
        center["lng"] = oneGeoObj.location.coordinates[1];

    }else if(oneGeoObj.geoType == "LINESTRING"){

        center["lat"] = oneGeoObj.location.coordinates[0][0];
        center["lng"] = oneGeoObj.location.coordinates[0][1];

    }else if(oneGeoObj.geoType == "POLYGON"){

        center["lat"] = oneGeoObj.location.coordinates[0][0][0];
        center["lng"] = oneGeoObj.location.coordinates[0][0][1];
    }
    // geoMapio.setCenter();
    geoMap.panTo(center);
    geoMap.setZoom(18);
}

// DELETE GEOFENCES
function deleteAllShape() {
  for (var i = 0; i < all_overlays.length; i++) {
    all_overlays[i].overlay.setMap(null);
  }
  all_overlays = [];
}
function resetAll(){
    $('input').val("")
    $('textarea').val("")
    $(".geo-type-fields").hide();
    var typee = $('#geoType').val()
        $("#GEOTYPE_"+typee).show();

    // geoMap.setZoom(5)
 if(markersGroup.length > 0){
        _.each(markersGroup,function(marker,i){
            marker.setMap(null);
        });
    }

    if(circlesGroup.length > 0){
        _.each(circlesGroup,function(circle,i){
            circle.setMap(null);
        });
    }

    if(polygonGroup.length > 0){
        _.each(polygonGroup,function(polygon,i){
            polygon.setMap(null);
        });
    }

    if(polylineGroup.length > 0){
        _.each(polylineGroup,function(polyline,i){
            polyline.setMap(null);
        });
    }
   
    deleteAllShape()
}
function proceedDelete(current_geofence_id,_id) {
     swal({
            title: "Confirmation",

            text: " Are you sure you want to delete this geofence?",
            type: "warning",
            confirmButtonClass: "btn-danger",
            showCancelButton: true,
            confirmButtonColor: '#E62365',
            icon: "warning",
            confirmButtonText: "Yes, Proceed"
        }).then(function (result) {
            if (result) {
                deleteEntityGeofence(current_geofence_id,_id,function (status, data) {
            if (status) {
                 swal({
                title: "Success",
                text: "Geofence Deleted Successfully!",
                type: "success",
                icon: "success",
                confirmButtonText: "Ok",
                confirmButtonClass: "btn-danger",
                confirmButtonColor: '#E62365'

                })
            .then(function (result) {
                if (result) {
                        loadGeoList();
                        geofenceInit()
             }
             })
            } else {
                 swal("Error", "Error in deleting Geofence", "error");
            }
    })
            }
        }); 
    
}
function deleteEntityGeofence(id, _id,cbk) {
    var group ="GEOFENCE"
    for(i=0;i<geodata.length;i++){
        if(_id==geodata[i]._id){
            group = geodata[i].group
        }
    }
    $.ajax({
        url: API_BASE_PATH + "/geofence/delete/" + API_TOKEN + "/" + id,
        type: 'DELETE',
        success: function (data) {
            //called when successful
            cbk(true, data);
        },
        error: function (e) {
            //called when there is an error
            //console.log(e.message);
            cbk(false, e);
        }
    });
}
function restoreRecord(){
    geofenceObj = {
        "group":"GEOFENCE",
        "name": "",
        "geoType": "",
        "label": "",
        "description": "",
        "coordinates": "",
        "radius": 50,
        "geometries": "",
        "locationSearch": "",
        "lat": "",
        "lng": ""
    };

    $("#locationSearch").val("");
}

// CREATE GEOFENCE dynamic-------------------
function upsertEntityGeofence(type){
   var TEXT =  $('.actionHead').html()
    var successText = "",successText="",btnText = ""
    if(TEXT== "Create Geofence"){
        successMsg= "Your Geofence has been Created."
        successText = "Created!"
        
        btnText = "Create Geofence"
    }else if(TEXT== "Update Geofence"){
         successMsg = "Your Geofence has been Updated."
         successText = "Updated"
         btnText = "Update Geofence"
    }

    var geoInputObj  = {};
    geoInputObj['coordinates'] = [];
    geoInputObj['description'] = geofenceObj.description;

    geoInputObj['geometries'] = {
        "type": "",
        "coordinates": []
    };
    
    if(geofenceObj.geoType == 'POINT'){

        geoInputObj['coordinates'] = [geofenceObj.lat,geofenceObj.lng];

    }else if(geofenceObj.geoType == 'LINESTRING'){

        geoInputObj['coordinates'] = geofenceObj.coordinatesGroup;

    }else if(geofenceObj.geoType == 'CIRCLE'){

        geoInputObj['coordinates'] = [geofenceObj.lat,geofenceObj.lng];
        geoInputObj['radius'] = $('#bskpCircleRadius').val() || geofenceObj.radius;

    }else if(geofenceObj.geoType == 'POLYGON'){

        geoInputObj['coordinates'] = [];
        geoInputObj.coordinates.push(geofenceObj.coordinatesGroup);
    }
    geofenceObj.name = $("#geoCreate #geofencename").val();
    geofenceObj.label = $("#geoCreate #labelGeo").val();
    geofenceObj.description = $("#geoCreate #description").val();

    geoInputObj['domainKey'] = DOMAIN_KEY;

    geoInputObj['group'] = "GEOFENCE";
    geoInputObj['name'] = geofenceObj.name ? geofenceObj.name :"";
    geoInputObj['geoType'] = geofenceObj.geoType;
    geoInputObj['label'] = geofenceObj.label;
    geoInputObj['description'] = geofenceObj.description;
    geoInputObj['coordinates'] = JSON.stringify(geoInputObj.coordinates);
    geoInputObj['createdAt'] = new Date().getTime();
    geoInputObj['entityId'] = guid();
    //  geoInputObj['radius'] = geofenceObj.radius;

    // geoInputObj['category1'] = geofenceObj.category1;
    geoInputObj['geometries']['type'] = geoInputObj.geoType;
    geoInputObj['geometries']['coordinates'] = geoInputObj.coordinates;
    geoInputObj['geometries'] = JSON.stringify(geoInputObj.geometries);
    $("input").css({"border":"1px solid #ccc","background":"#fff"});

   if(!geofenceObj.name){

        $("#geofencename").css({"border":"1px solid red","background":"#ff00000d"}).focus();
        errorMsg('Geofence Name is Required');

    }else if(!geofenceObj.geoType){

        $("#geoType").css({"border":"1px solid red","background":"#ff00000d"}).focus();
        errorMsg('Geofence Type is Required');

    }else if(!geofenceObj.label){

        $("#labelGeo").css({"border":"1px solid red","background":"#ff00000d"}).focus();
        errorMsg('Label is Required');

    } else{

        if(geofenceObj.geoType === 'POINT'){

            if(!$("#pointLat").val()){

                $("#pointLat").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Lat. is required for points');
                return false;

            }else if(!$("#pointLong").val()){

                $("#pointLong").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Long. is required for points');
                return false;

            }

        }else if(geofenceObj.geoType === 'CIRCLE'){

            if(!$("#bskpLat").val()){

                $("#bskpLat").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Lat. is required for circle');
                return false;

            }else if(!$("#bskpLong").val()){

                $("#bskpLong").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Long. is required for circle');
                return false;

            }else if(!$("#bskpCircleRadius").val()){

                $("#bskpCircleRadius").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Radius is required for circle');
                return false;

            }

        }else if(geofenceObj.geoType === 'POLYGON'){

            if(!$("#polygonCoordinates").val()){

                $("#polygonCoordinates").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Coordinates is required for polygon');
                return false;

            }

        }else if(geofenceObj.geoType === 'LINESTRING'){

            if(!$("#linestringCoordinates").val()){

                $("#linestringCoordinates").css({"border":"1px solid red","background":"#ff00000d"}).focus();
                errorMsg('Coordinates is required for linestring');
                return false;

            }

        }

       $("#geoCreateSubmit").attr('disabled', 'disabled');
       $("#geoCreateSubmit").html('<i class="fa fa-spinner fa-spin"></i> Processing...');
      
                $.ajax({
                    url: API_BASE_PATH + "/geofence/upsert/" + API_TOKEN+"?geotype="+geoInputObj.geoType,
                    data: JSON.stringify(geoInputObj),
                    contentType: "application/json",
                    type: 'POST',
                    success: function (res) {
                        $("#geoCreateSubmit").removeAttr('disabled');
                        $("#geoCreateSubmit").html(btnText);
                        if(res){

                            $("#geoCreate input").val("");
                            $("#geoCreate textarea").val("");
                            $("#geoCreate #geoType").val("POINT");
                            mapTools("DEFAULT")

                            setTimeout(function () {
                                loadGeoList();
                                geofenceInit()
                            },1000);
                            swal(successText, successMsg, "success");
                            closeModal()
                        }else{
                            swal("Error", "Try Again", "error");
                        }
                    },
                    error: function (err) {
                        $("#geoCreateSubmit").removeAttr('disabled');
                        $("#geoCreateSubmit").html(btnText);
                        if(err.status === 417){
                            swal("417 Error", "Invalid Parameters, Check Your Geofence Details!"+err, "error");
                        }
                    }
                });

    }
}

// MAP TOOLS
function GetGoogleApiKey(data) {
	$.ajax({
		url: API_BASE_PATH + "/domain/property/get/" + API_TOKEN+"/"+Google,
        // ata: JSON.stringify(data),
		contentType: "application/json",
		type: 'GET',
		success: function (data) {
			//called when successful
			var key=JSON.parse(data.value)
		
			  var script_tag = document.createElement('script');
            script_tag.setAttribute("type", "text/javascript");
	    	script_tag.setAttribute("src", "https://maps.googleapis.com/maps/api/js?key="+key.apiKey+"&libraries=visualization,places,drawing&callback=initialize");
		  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
		   
		 },
		 error: function (e) {
			//called when there is an error
// 			console.log(false, e);
		}
	});
}
function mapTools(flag){
    resetAll()
    $(".map-top-tools .min-tool-btn").removeClass("active");
    $("#"+flag).addClass("active");
    $("#geoType").val(flag);

    if(flag == "DEFAULT"){

        drawingManager.setDrawingMode(null);

    }else{

        $(".geo-type-fields").hide();
        $("#GEOTYPE_"+flag).show();


        if(flag == "POINT"){    //Draw Point Tool
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.MARKER);
            geofenceObj.geoType = "POINT";

        }else if(flag == "CIRCLE"){     //Draw Circle Tool
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.CIRCLE);
            geofenceObj.geoType = "CIRCLE";

        }else if(flag == "POLYGON"){    //Draw Polygon Tool
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
            geofenceObj.geoType = "POLYGON";

        }else if(flag == "LINESTRING"){    //Draw Linestring Tool
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE);
            geofenceObj.geoType = "LINESTRING";

        }else if(flag == "ENVELOPE"){    //Draw Envelope Tool
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
            geofenceObj.geoType = "ENVELOPE";

        }else{    //Select

            drawingManager.setDrawingMode(null);
        }
    }
}

function overlayClickListener(overlay) {

    google.maps.event.addListener(overlay, "mouseup", function(event){
        // $('#bskpCoordinatesBox').val(overlay.getPath().getArray());
        $('#bskpCoordinatesBox').val(JSON.stringify(geofenceObj.coordinatesGroup));
    });
}
function toggleGeoType() {
    resetAll();
    if ($("#geofencetype").val() === 'CIRCLE') {
        $(".geoBody").html($("#geoCircle").html());

        drawingManager.setDrawingMode(google.maps.drawing.OverlayType.CIRCLE);

    } else {
        $(".geoBody").html($("#geoPolygon").html());
        drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);

    }
}


// GEOFENCE CREATION MODAL
function openModal(type,_id){
    if(type==1){
         pageLoader()
        $('.map-top-tools').addClass('d-block').removeClass('d-none')
        resetAll()
        
        $('.tableContainer').addClass('d-none').removeClass('d-block')
        var mapHeight = $("#mapGeo").height();
        $(".geofenceAdd").addClass('d-block').removeClass('d-none');
        $("form#geoCreate")[0].reset();
        $('.geofenceAdd').css('height', ($(window).height() + 'px'));
        $('.geofenceAdd').css('overflow-y','auto')
        drawingManager.setOptions({
            drawingControl: false
        });
        $('.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom').css({"top":340,"left:":0})
        $('button.gm-control-active.gm-fullscreen-control').css({"top":340,"left:":0})
        $('.actionHead').html('Create Geofence')
        $("#geoCreateSubmit").html("Create Geofence");
    }else if(type==2){
        
         pageLoader()
        $('.map-top-tools').addClass('d-block').removeClass('d-none')
        $('.tableContainer').addClass('d-none').removeClass('d-block')
        var mapHeight = $("#mapGeo").height();
        $(".geofenceAdd").addClass('d-block').removeClass('d-none');
        $("form#geoCreate")[0].reset();
        $('.geofenceAdd').css('height', ($(window).height() + 'px'));
        $('.geofenceAdd').css('overflow-y','auto')
        $("#geoCreateSubmit").html("Update Geofence");
        drawingManager.setOptions({
            drawingControl: false
        });
        $('.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom').css({"top":340,"left:":0})
        $('button.gm-control-active.gm-fullscreen-control').css({"top":340,"left:":0})
        $('.actionHead').html('Update Geofence')
        var EDITDATAOBJ = {}
        for(i=0;i<geodata.length;i++){
            if(_id==geodata[i]._id){
            EDITDATAOBJ = geodata[i]
            }
        }
        mapTools(EDITDATAOBJ.geoType)
        $('#geofencename').val(EDITDATAOBJ.name)
        $('#labelGeo').val(EDITDATAOBJ.label)
        $('#description').val(EDITDATAOBJ.description)
        drawingManager.setDrawingMode(null);
        if(EDITDATAOBJ.geoType == "CIRCLE"){
            $('#bskpLat').val(JSON.stringify(EDITDATAOBJ.coordinates[0]))
            $('#bskpLong').val(JSON.stringify(EDITDATAOBJ.coordinates[1]))
            $('#bskpCircleRadius').val(EDITDATAOBJ.radius)
             geofenceObj.lat = EDITDATAOBJ.coordinates[0];
            geofenceObj.lng = EDITDATAOBJ.coordinates[1];
            geofenceObj.radius = EDITDATAOBJ.radius
            var val = EDITDATAOBJ
            val.location["coordinates"] = val.location.coordinates;

                var center= {
                    lat : val.location.coordinates[0],
                    lng : val.location.coordinates[1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div><b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/oval.png' > CIRCLE</p>"+
                    "</div>" +
                    "</div>"
                });
                // Create marker
                // var marker = new google.maps.Marker({
                //     map: geoMap,
                //     position: new google.maps.LatLng(center),
                //     title: val.name,
                //     animation: google.maps.Animation.DROP,
                //     icon:icon
                // });
                // marker.addListener('click', function() {
                //     infowindow.open(geoMap, marker);
                //     geoMap.panTo(center);
                //     geoMap.setZoom(17);
                // });
                // infowindow.open(geoMap, marker);
                var geofenceCircle = new google.maps.Circle({
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#FF0000',
                    fillOpacity: 0.35,
                    map: geoMap,
                    center: center,
                    radius: Number(val.location.radius),
                     editable:true,
                     draggable:true
                });
         geoMap.panTo(center);
        geoMap.setZoom(16);
        // geofenceCircle.addListener('mousedown', function(event){
                        
      var lat = geofenceCircle.getCenter().lat();
            var lng = geofenceCircle.getCenter().lng();

            geofenceObj.lat = lat;
            geofenceObj.lng = lng;
            $("#bskpLat").val(lat);
            $("#bskpLong").val(lng);
            // openCreateGeoModal();
            //Common Circle Drag Listener
            geofenceCircle.addListener('radius_changed', function(event){
                
                if(geofenceCircle.getRadius() >=10 && geofenceCircle.getRadius() <= 250){
                    geofenceObj.radius = geofenceCircle.getRadius();
                $("#bskpCircleRadius").val(geofenceObj.radius);
                }else{
                    geofenceCircle.setRadius(250)
                    $("#bskpCircleRadius").val(250)
                }
                
                // geofenceObj.radius = geofenceCircle.getRadius();
                
                // $("#bskpCircleRadius").val(350).val(geofenceObj.radius);
            });

            //Common Circle Drag Listener
            geofenceCircle.addListener('center_changed', function(event){

                var lat = geofenceCircle.getCenter().lat();
                var lng = geofenceCircle.getCenter().lng();
                geofenceObj.lat = lat;
                geofenceObj.lng = lng;
                $("#bskpLat").val(lat);
                $("#bskpLong").val(lng);
            });

            if(marker){

                geofenceCircle.bindTo('center', marker, 'position');
                geofenceCircle._myCircle = geofenceCircle;

                marker.addListener('dragend', function(event){
                    geofenceObj.lat = event.latLng.lat();
                    geofenceObj.lng = event.latLng.lng();

                    $("#bskpLat").val(geofenceObj.lat);
                    $("#bskpLong").val(geofenceObj.lng);
                });

            }

            drawingManager.setDrawingMode(null)

// })
          

                circlesGroup.push(geofenceCircle);
            
            
        }else if(EDITDATAOBJ.geoType == "POLYGON"){
            $('#polygonCoordinates').val( JSON.stringify(EDITDATAOBJ.coordinates))
             geofenceObj.coordinatesGroup = EDITDATAOBJ.coordinates
            var val = EDITDATAOBJ
             val.location["coordinates"] = val.location.coordinates;

                var center= {
                    lat : val.location.coordinates[0][0][0],
                    lng : val.location.coordinates[0][0][1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div><b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/polygon.png' > POLYGON</p>"+
                    "</div>" +
                    "</div>"
                });

                // Create marker
                // var marker = new google.maps.Marker({
                //     map: geoMap,
                //     position: new google.maps.LatLng(center),
                //     title: val.name,
                  
                //     animation: google.maps.Animation.DROP,
                //     icon:icon
                // });
                // marker.addListener('click', function() {
                //     infowindow.open(geoMap, marker);
                //     geoMap.panTo(center);
                //     geoMap.setZoom(17);
                // });
                // infowindow.open(geoMap, marker);
                

                var polyCoords = [];
                _.each(val.location.coordinates[0],function(val,i){

                    var oneCoord = {};
                    oneCoord["lat"] = val[0];
                    oneCoord["lng"] = val[1];
                    polyCoords.push(oneCoord);
                });

                // Construct the polygon.
                var geoPoly = new google.maps.Polygon({
                    paths: polyCoords,
                    strokeColor: '#FF0000',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#FF0000',
                    fillOpacity: 0.35,
                      editable:true
                });
                geoPoly.setMap(geoMap);
                 geoPoly.addListener('mouseup', function() {

                var temp=[];
            _.each(geoPoly.getPath().getArray(),function(val,i){

                 var st2 = [];
                st2.push(val.lat());
                st2.push(val.lng());
                temp.push(st2);
            });

            if(!(_.isEqual(temp[0],temp[temp.length-1]))){  //Add polygon close coordinate check
                temp.push(temp[0]);
            }
                geofenceObj.coordinatesGroup = temp;
                $('#polygonCoordinates').val(JSON.stringify(temp));
                drawingManager.setDrawingMode(null)
                });
                polygonGroup.push(geoPoly);
            
        }else if(EDITDATAOBJ.geoType == "LINESTRING"){
            
            $('#linestringCoordinates').val(JSON.stringify(EDITDATAOBJ.coordinates))
            geofenceObj.coordinatesGroup = EDITDATAOBJ.coordinates
                var val = EDITDATAOBJ
                val.location["coordinates"] = val.location.coordinates;

                var center= {
                    lat : val.location.coordinates[0][0],
                    lng : val.location.coordinates[0][1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div>" +
                    "<b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/polyline.png' > LINESTRING</p>"+
                    "</div>" +
                    "</div>"
                });

                // Create marker
                // var marker = new google.maps.Marker({
                //     map: geoMap,
                //     position: new google.maps.LatLng(center),
                //     title: val.name,
                //     animation: google.maps.Animation.DROP,
                //     icon:icon
                // });
                // marker.addListener('click', function() {
                //     infowindow.open(geoMap, marker);
                //     geoMap.panTo(center);
                //     geoMap.setZoom(17);
                // });
                // infowindow.open(geoMap, marker);

                var lineCoords = [];
                _.each(val.location.coordinates,function(val,i){

                    var oneCoord = {};
                    oneCoord["lat"] = val[0];
                    oneCoord["lng"] = val[1];
                    lineCoords.push(oneCoord);
                });

                var geoLineString = new google.maps.Polyline({
                    path: lineCoords,
                    strokeColor: "#FF0000",
                    strokeOpacity: 1.0,
                    strokeWeight: 2,
                     editable:true
                });
                geoLineString.setMap(geoMap);
                
                geoLineString.addListener('mouseup', function() {

                var temp=[];
            _.each(geoLineString.getPath().getArray(),function(val,i){

                 var st2 = [];
                st2.push(val.lat());
                st2.push(val.lng());
                temp.push(st2);
            });

            geofenceObj.coordinatesGroup = temp;
            $('#linestringCoordinates').val(JSON.stringify(temp));
            drawingManager.setDrawingMode(null)
                });
                polylineGroup.push(geoLineString);

        }else if(EDITDATAOBJ.geoType == "POINT"){
            $('#pointLat').val(JSON.stringify(EDITDATAOBJ.coordinates[0]))
            $('#pointLong').val(JSON.stringify(EDITDATAOBJ.coordinates[1]))
            var val = EDITDATAOBJ
             geofenceObj.lat = EDITDATAOBJ.coordinates[0];
            geofenceObj.lng = EDITDATAOBJ.coordinates[1];
            val.location["coordinates"] = val.location.coordinates;
                val["description"] = val.description;

                var center= {
                    lat : val.location.coordinates[0],
                    lng : val.location.coordinates[1]
                };

                var icon = {
                    url: "images/map/marker_red.png"
                };

                var infowindow = new google.maps.InfoWindow({
                    content:
                    "<div><b style='text-transform: capitalize;font-size: 16px;color: #F62459;'><i class='fa fa-map mr-2'></i>"+val.name+"</b></br>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;text-transform: capitalize;margin-bottom:0px;width:200px;'>"+val.description+"</p>"+
                    "<div style='margin-top:10px;'>" +
                    "<p style='font-size: 12px;color: #888;display:inline-block;padding: 5px 6px;background: #eee;border-radius: 3px;margin-right: 5px;margin-bottom: 0px;'>"+val.label+"</p>" +
                    "<p style='font-size: 13px;color: #767676;margin-top:8px;'><img src='images/map/pin.png' > POINT</p>"+
                    "</div>" +
                    "</div>"
                });

                // Create marker
                var marker = new google.maps.Marker({
                    map: geoMap,
                    position: new google.maps.LatLng(center),
                    title: val.name,
                    animation: google.maps.Animation.DROP,
                     draggable:true,
                     clickable: true,
                     editable: true,
                    icon:icon,
                    
                });
                marker.addListener('click', function() {
                    // infowindow.open(geoMap, marker);
                    geoMap.panTo(center);
                    geoMap.setZoom(17);
                });
                marker.addListener('mouseup', function() {
                    var lat = marker.getPosition().lat()
                    var lng = marker.getPosition().lng()
                    $('#pointLat').val(lat)
                    $('#pointLong').val(lng)
                     geofenceObj.lat = lat;
                     geofenceObj.lng = lng;
            // $('#linestringCoordinates').val(JSON.stringify(temp));
                    drawingManager.setDrawingMode(null)
                });
                
                markersGroup.push(marker)
                 

        }
        
    }
       
}
function closeModal() {
    $('.transpernetProcessing').removeClass('hide')
    setTimeout(function() {
        $('.transpernetProcessing').addClass('hide')
        drawingManager.setOptions({
        drawingControl: false
    });
    drawingManager.setDrawingMode(null);
    $("#mydiv").css({top: 200, left: 200});
    $('.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom').css({"top":340,"left:":0})
        $('button.gm-control-active.gm-fullscreen-control').css({"top":340,"left:":0})
    markerList = []
    loadGeoList();
    geofenceInit()
    $('.tableContainer').addClass('d-block').removeClass('d-none');
     $(".geofenceAdd").addClass('d-none').removeClass('d-block');
     
     $(".map-top-tools").addClass('d-none').removeClass('d-block');
    }, 500);
    
}
$(".GListheader").click(function () {
    $header = $(this);
    $content = $header.next();
    $content.slideToggle(500, function () { });
});
function guid() {
	 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

//Notifications
function errorMsg(msg) {

    // $(".errorFeedBack").html("<i class='fa fa-exclamation-triangle'></i> "+msg);
    $("#snackbar").html("<i class='fa fa-exclamation-triangle'></i> " + msg);
    var width = $(".errorFeedBack").outerWidth();
    var totalWidth = $(document).width();
    var position = (parseInt(totalWidth) - parseInt(width)) / 2;
    $(".errorFeedBack").css({
        'left': position - 10
    });

    var $window = $(window),
        $stickyEl = $('.feedBack');

    var windowTop = $window.scrollTop();
    $(".errorFeedBack").css('top', 105);

    $(".errorFeedBack").show().delay(2500).fadeOut();

    snackBar();
    // $.growl.error({title:"<i class='fa fa-exclamation-triangle'></i> Error", message: msg });
}
function snackBar() {
    $("#snackbar").addClass('show');
    setTimeout(function () {
        $("#snackbar").removeClass('show');
    }, 2000);
}
function pageLoader(){
    $('.transpernetProcessing').removeClass('hide')
    setTimeout(function() {
        $('.transpernetProcessing').addClass('hide')
    }, 300);
}
/* TABLE START */
.tableContainer {
    border:1px solid #d3d3d3;
    position:absolute;
    bottom:0;
    right:0;
    width:100%;
    background:#fff;
}
.tableContainer div {
    width:100%;
}
.tableContainer .GListheader {
  background-color: #fff;
    cursor: pointer;
    font-weight: bold;
    color: rgb(109, 109, 109);
    z-index: 0;
    border-bottom: 2px solid rgb(109, 109, 109);
}

.tableContainer .tbl-style {
    display: none;
    background:#fff;
    margin:0;
}
.table thead th{
    font-weight: 600 !important;
    text-transform: capitalize !important;
    font-size: 12px !important;
    letter-spacing: 0.5px !important;
    color:rgb(109, 109, 109) !important;
    background: rgb(109, 109, 109,0.12) !important;
}
table.dataTable tbody th, table.dataTable tbody td{
     font-size: 12px !important;
     font-family: Poppins,sans-serif;
    color: #212529;
    font-weight:500;
    /*text-align:left;*/
    /*padding-left: 0px;*/
}

.dataTables_scrollHeadInner,.dataTables_scrollHeadInner table{
    width:100% !important;
}

.dataTables_length label{
    float:left !important;
}
.accordion-toggle:after {
    font-family: 'FontAwesome';
    content: "\f078";    
    float: right;
}
table.dataTable thead .sorting_asc, table.dataTable thead .sorting_desc, table.dataTable thead .sorting{
        width: 25% !important;
        padding-left: 30px;
}
.accordion-opened .accordion-toggle:after {    
    content: "\f054";    
}
/* TABLE END */
/*Mapping START*/
.geofenceAdd{
    position:absolute;
    top:0;
    width:35%;
    right:0;
    border: 1px solid #ddd;
    box-shadow: -5px 0 5px -5px #aaa;
    background:#fff;
    margin:0;
}
.map-top-tools {
    display: inline-block;
    position: absolute;
    top: 200px;
    left: 10px;
    z-index: 1;
    background: #fff;
    text-align: center;
    width: 40px;
    border-radius: 3px;
    box-shadow: 0.2px 0.8px 0.7px #999;
}

.map-tools {
    padding: 2px;
    /* background: #F62459; */
    font-size: 11px;
    color: #ffffff;
    font-weight: 600;
}
.map-top-tools .min-tool-btn {
    padding: 10px;
    margin-top: 2px;
    font-size: 18px;
    color: #666666;
    text-align: center;
    width: 100%;
    border: 1px solid #ffffff;
    background:transparent;
}
.map-top-tools .min-tool-btn:hover {
    background: #fff;
    color: #666;
    border: 1px solid #666;
}

.actionHead{
      font-size: 14px;
    font-weight: 600;
    margin-top: 5px;
    margin-left: 3%;
}

.pac-target-input:not(:-webkit-autofill){
    animation-name:endBrowserAutofill;
}

.geoCreateHeader{
        padding: 10px 0;
    border-bottom: 1px solid #ddd;
    position: fixed;
    width: 100%;
    z-index: 10;
    background: #fff;
}

.gm-ui-hover-effect{
    top: 5px !important;
    right: 0px  !important;
}
.gm-ui-hover-effect:focus{
    outine:none !important;
}
.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom{
    top: 25px !important;
    left: 0px !important;
    right: 0px !important;
    bottom: auto !important;
}
button.gm-control-active.gm-fullscreen-control{
    top: 0px !important;
    left: 0px !important;
}
.gm-style-mtc{
    top:0px;
    left:50px;
}
.gm-svpc{
    top: 25px !important;
}
/*Mapping END*/

.transpernetProcessing {
    position: absolute;
    width: 100%;
    background: #ffffffc9;
    height: 100%;
    z-index: 100;
    top:0;
}

 .transpernetProcessing .loader {
    text-align: center;
    margin-top: 15%;
}
  
  
  #snackbar.show {
    visibility: visible;
    /*-webkit-animation: fadein 0.5s;*/
    animation: fadein 0.5s;
}
#snackbar {
    visibility: hidden;
    min-width: 250px;
    margin-left: -125px;
    background-color: #333;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    padding: 16px;
    position: fixed;
    z-index: 999999999999;
    left: 50%;
    top: 100px;
    height: 50px;
}
https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js
https://unpkg.com/sweetalert/dist/sweetalert.min.js
https://pro.fontawesome.com/releases/v5.10.0/css/all.css

Sample Output

3570

Manage Locations