JavaScript Google Maps и Маркер передают правильный идентификатор - PullRequest
0 голосов
/ 18 мая 2018

Моя проблема в том, что, когда я перетаскиваю маркер, я не получаю правильный идентификатор, который назначен маркеру.Всегда тянется идентификатор 12. Моя цель - иметь список маркеров от 1 до N, и когда я перетаскиваю маркер на новое место, я хочу иметь возможность получить правильный идентификатор, чтобы я мог обновить базу данных с новымGPS местоположения.Все остальное в скрипте, кажется, работает должным образом, за исключением передачи правильного идентификатора при выборе.

<script>

    var markers = [

                {
                    "ID": '8',
                    "Latitude": '39.336379',
        "Longitude": '-76.420309',

        "Name": 'Lowes',
                "Address1": '78 White Lane',
    }

                      ,

                {
                    "ID": '12',
                    "Latitude": '39.334017',
        "Longitude": '-76.421612',

        "Name": 'Home Depot',
                "Address1": '124 Yew Rd',
    }
    ];


    var gmarkers = [];

    function initMap() {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.SATELLITE,
            gestureHandling: 'greedy'

        };
        var infoWindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.Name,
                draggable: true,
                markerID: data.ID
            });
            gmarkers[data.ID] = marker;
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    map.panTo(marker.getPosition());
                    infoWindow.setContent(data.Address1);
                    infoWindow.open(map, marker);
                    map.setZoom(19);
                });

            })(marker, data);



            google.maps.event.addListener(marker, 'dragend', function (evt) {
                document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(6) + ' Current Lng: ' + evt.latLng.lng().toFixed(6) + '</p>';
                var docksObject = { ID: marker.markerID, Lat: evt.latLng.lat().toFixed(6), Long: evt.latLng.lng().toFixed(6), isState: false, isActive: true }
                //showSwal('warning-message-and-cancel', docksObject);
            });



        }


    }
    function myClick(markerID) {
        google.maps.event.trigger(gmarkers[markerID], 'click');
    }





    function updateLatLong(dockdata) {


        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            //withCredentials: false,
            url: '../Docks.asmx/UpdateDocksMethod',
            dataType: "json",
            data: "{'ID':'" + dockdata.ID + "', 'LAT':'" + dockdata.Lat + "','LONG':'" + dockdata.Long + "', 'isState':'" + dockdata.isState + "','isActive':'" + dockdata.isActive + "'}",
            //data: "{'ID':'" + dockdata.ID + "', 'LAT':'" + dockdata.Lat + "','LONG':'" + dockdata.Long + "', 'isState':'" + dockdata.isState +  "'}",
            //async: false,
            success: function (response) {
                location.reload();




            },
            error: function (response) {

                alert("Error")
                console.log(response);
            }
        });


    }

    function showSwal(type, dockinfo) {
        if (type == 'basic') {
            swal("Here's a message!");

        } else if (type == 'title-and-text') {
            swal("Here's a message!", "It's pretty, isn't it?")

        } else if (type == 'success-message') {
            swal("Good job!", "You clicked the button!", "success")

        } else if (type == 'warning-message-and-confirmation') {
            swal({
                title: "Are you sure?",
                text: "You will not be able to recover this imaginary file!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn btn-info btn-fill",
                confirmButtonText: "Yes, delete it!",
                cancelButtonClass: "btn btn-danger btn-fill",
                closeOnConfirm: false,
            }, function () {
                swal("Deleted!", "Your imaginary file has been deleted.", "success");
            });

        } else if (type == 'warning-message-and-cancel') {
            swal({
                title: "Are you sure?",
                text: "You will not be able to undo the Lat/Long change.",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes, change the Lat/Long",
                cancelButtonText: "No, cancel the change!",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    swal("Update!", "The Lat/Long has been updated.", "success");
                    // Call and update the database with new lat/long
                    updateLatLong(dockinfo);

                } else {
                    swal("Cancelled", "The system has not been updated", "error");
                }
            });

        } else if (type == 'custom-html') {
            swal({
                title: 'HTML example',
                html: 'You can use <b>bold text</b>, ' +
                '<a href="http://github.com">links</a> ' +
                'and other HTML tags'
            });

        } else if (type == 'auto-close') {
            swal({
                title: "Auto close alert!",
                text: "I will close in 2 seconds.",
                timer: 2000,
                showConfirmButton: false
            });
        } else if (type == 'input-field') {
            swal({
                title: 'Input something',
                html: '<p><input id="input-field" class="form-control">',
                showCancelButton: true,
                closeOnConfirm: false,
                allowOutsideClick: false
            },
                function () {
                    swal({
                        html: 'You entered: <strong>' +
                        $('#input-field').val() +
                        '</strong>'
                    });
                })
        }
    }


</script>

1 Ответ

0 голосов
/ 18 мая 2018

Смежный вопрос: Google Maps - центрирование карты при нажатии маркера

Два варианта:

  1. переместить функцию прослушивателя событий dragend внутри замыкания наmarker
  2. используйте this для ссылки на маркер внутри функции прослушивания щелчка
google.maps.event.addListener(marker, 'dragend', function(evt) {
  document.getElementById('current').innerHTML = '<p>Marker ID='+this.markerID+' dropped: Current Lat: ' + evt.latLng.lat().toFixed(6) + ' Current Lng: ' + evt.latLng.lng().toFixed(6) + '</p>';
  var docksObject = {
    ID: this.markerID,
    Lat: evt.latLng.lat().toFixed(6),
    Long: evt.latLng.lng().toFixed(6),
    isState: false,
    isActive: true
  }
  //showSwal('warning-message-and-cancel', docksObject);
});

подтверждение концепции скрипта

screenshot of map after dragging markerID 8

фрагмент кода:

var markers = [

  {
    "ID": '8',
    "Latitude": '39.336379',
    "Longitude": '-76.420309',

    "Name": 'Lowes',
    "Address1": '78 White Lane',
  }

  ,

  {
    "ID": '12',
    "Latitude": '39.334017',
    "Longitude": '-76.421612',

    "Name": 'Home Depot',
    "Address1": '124 Yew Rd',
  }
];


var gmarkers = [];

function initMap() {
  var mapOptions = {
    center: new google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
    zoom: 16,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    gestureHandling: 'greedy'

  };
  var infoWindow = new google.maps.InfoWindow();
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  for (i = 0; i < markers.length; i++) {
    var data = markers[i]
    var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: data.Name,
      draggable: true,
      markerID: data.ID
    });
    gmarkers[data.ID] = marker;
    (function(marker, data) {
      google.maps.event.addListener(marker, "click", function(e) {
        map.panTo(marker.getPosition());
        infoWindow.setContent(data.Address1);
        infoWindow.open(map, marker);
        map.setZoom(19);
      });

    })(marker, data);

    google.maps.event.addListener(marker, 'dragend', function(evt) {
      document.getElementById('current').innerHTML = '<p>Marker ID=' + this.markerID + ' dropped: Current Lat: ' + evt.latLng.lat().toFixed(6) + ' Current Lng: ' + evt.latLng.lng().toFixed(6) + '</p>';
      var docksObject = {
        ID: this.markerID,
        Lat: evt.latLng.lat().toFixed(6),
        Long: evt.latLng.lng().toFixed(6),
        isState: false,
        isActive: true
      }
      console.log("dragged marker=" + this.markerID)
      //showSwal('warning-message-and-cancel', docksObject);
    });
  }
}

function myClick(markerID) {
  google.maps.event.trigger(gmarkers[markerID], 'click');
}

function updateLatLong(dockdata) {
  $.ajax({
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    //withCredentials: false,
    url: '../Docks.asmx/UpdateDocksMethod',
    dataType: "json",
    data: "{'ID':'" + dockdata.ID + "', 'LAT':'" + dockdata.Lat + "','LONG':'" + dockdata.Long + "', 'isState':'" + dockdata.isState + "','isActive':'" + dockdata.isActive + "'}",
    //data: "{'ID':'" + dockdata.ID + "', 'LAT':'" + dockdata.Lat + "','LONG':'" + dockdata.Long + "', 'isState':'" + dockdata.isState +  "'}",
    //async: false,
    success: function(response) {
      location.reload();
    },
    error: function(response) {

      alert("Error")
      console.log(response);
    }
  });
}

function showSwal(type, dockinfo) {
  if (type == 'basic') {
    swal("Here's a message!");

  } else if (type == 'title-and-text') {
    swal("Here's a message!", "It's pretty, isn't it?")

  } else if (type == 'success-message') {
    swal("Good job!", "You clicked the button!", "success")

  } else if (type == 'warning-message-and-confirmation') {
    swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      type: "warning",
      showCancelButton: true,
      confirmButtonClass: "btn btn-info btn-fill",
      confirmButtonText: "Yes, delete it!",
      cancelButtonClass: "btn btn-danger btn-fill",
      closeOnConfirm: false,
    }, function() {
      swal("Deleted!", "Your imaginary file has been deleted.", "success");
    });

  } else if (type == 'warning-message-and-cancel') {
    swal({
      title: "Are you sure?",
      text: "You will not be able to undo the Lat/Long change.",
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "Yes, change the Lat/Long",
      cancelButtonText: "No, cancel the change!",
      closeOnConfirm: false,
      closeOnCancel: false
    }, function(isConfirm) {
      if (isConfirm) {
        swal("Update!", "The Lat/Long has been updated.", "success");
        // Call and update the database with new lat/long
        updateLatLong(dockinfo);

      } else {
        swal("Cancelled", "The system has not been updated", "error");
      }
    });

  } else if (type == 'custom-html') {
    swal({
      title: 'HTML example',
      html: 'You can use <b>bold text</b>, ' +
        '<a href="http://github.com">links</a> ' +
        'and other HTML tags'
    });

  } else if (type == 'auto-close') {
    swal({
      title: "Auto close alert!",
      text: "I will close in 2 seconds.",
      timer: 2000,
      showConfirmButton: false
    });
  } else if (type == 'input-field') {
    swal({
        title: 'Input something',
        html: '<p><input id="input-field" class="form-control">',
        showCancelButton: true,
        closeOnConfirm: false,
        allowOutsideClick: false
      },
      function() {
        swal({
          html: 'You entered: <strong>' +
            $('#input-field').val() +
            '</strong>'
        });
      })
  }
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="current"></div>
<div id="map"></div>
...