JavaScript Google地图和标记传递正确的ID

时间:2018-05-18 13:41:11

标签: javascript google-maps google-maps-api-3 google-maps-markers

我的问题是当我拖动标记时,我没有获得分配给标记的正确ID。它总是拉出12的ID。我的目标是有一个标记1到N的列表,当我将标记拖动到新位置时,我希望能够获得正确的ID,以便我可以更新数据库与新的GPS位置。除了在选择时传递正确的ID之外,脚本中的其他所有内容似乎都按预期工作。

<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 :(得分:0)

相关问题:Google Maps - center map on marker click

两个选项:

  1. dragend
  2. 的闭包内移动marker事件侦听器函数
  3. 使用this引用点击侦听器功能
  4. 中的标记
    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);
    });
    

    proof of concept fiddle

    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>