在单选按钮之间切换会导致重复坐标

时间:2013-07-17 18:55:42

标签: jquery google-maps radio-button duplicates jquery-gmap3

我遇到了一点腌渍。我有一个工具,利用jQuery的插件gMap3,允许用户在编写JSON数组,删除引脚或地址之间进行选择。该工具将JSON数组吐出到<textarea>中,以便以后轻松获取信息。唯一的问题是,当选择“地址”并且用户决定选择另一个选项如“拖动N'掉落”然后返回“地址”并输入新地址时,会创建重复坐标。任何帮助将不胜感激!

JSFIDDLE

情境:

  1. 点击选择中的地址。
  2. 在输入中键入任意地址,然后单击添加。
  3. 点击选择中的拖放,然后再选择地址。
  4. 这次在输入中输入其他地址,点击添加,然后在<textarea>
  5. 中看到重复的坐标

    代码:

    $(document).ready(function() {  
    
    //////// GMAP3 JSON ARRAY //////// 
    
    var mapOpts = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        navigationControl: true,
        scrollwheel: true,
        disableDoubleClickZoom: true,
        streetViewControl: false,
    }; 
    
    $(".gmap3").gmap3({
            map:{
            options: mapOpts
            }
    
        });
    
    $.mapArray = function(){
    
    $('#show_array').click(function(){
    
    $('.gmap3').gmap3('clear', 'markers');
    
      var coordinates = $("#geofenceCoords_array").val();
      var jsonObj = jQuery.parseJSON(coordinates);
      var addBtn = $("#show_array"); 
    
      var iconValues =
      new google.maps.MarkerImage('http://www.mindboxdesigns.com/test-images/map_marker_default.png', //icon url
      new google.maps.Size(28.0, 43.0),
      new google.maps.Point(0, 0),
      new google.maps.Point(14.0, 43.0));
    
    
      var shadowValues =
      new google.maps.MarkerImage('http://www.mindboxdesigns.com/test-images/map_marker_default_shadow.png', //icon shadow url
      new google.maps.Size(50.0, 43.0),
      new google.maps.Point(0, 0),
      new google.maps.Point(14.0, 43.0)); 
    
        $(".gmap3").gmap3({
        getlatlng:{
            callback: function(results){
              var markers=[];
              $.each(jsonObj, function(i, item) {
    
              var marker = new Object();
                  marker.lat = jsonObj[i].latitude;
                  marker.lng = jsonObj[i].longitude;
                  marker.options = new Object();
                  marker.options.icon = iconValues;
                  marker.options.shadow = shadowValues;
                  markers.push(marker);
              });
    
    
              $(".gmap3").gmap3({
                marker:{
                  values: markers,
                  options: {draggable: false,
                  animation: google.maps.Animation.DROP
                  },
    
              },
              autofit:{maxZoom: 14},
            });
          }
        }
        });
    });
        }
    
    //////// GMAP3 DRAG AND DROP ////////
    
     $.mapDrop = function(){
    
      var iconValues =
      new google.maps.MarkerImage('http://www.mindboxdesigns.com/test-images/map_marker_default.png', //icon url
      new google.maps.Size(28.0, 43.0),
      new google.maps.Point(0, 0),
      new google.maps.Point(14.0, 43.0));
    
      var shadowValues =
      new google.maps.MarkerImage('http://www.mindboxdesigns.com/test-images/map_marker_default_shadow.png', //icon shadow url
      new google.maps.Size(50.0, 43.0),
      new google.maps.Point(0, 0),
      new google.maps.Point(14.0, 43.0)); 
    
     function genId() {
            return '' + (new Date()).getTime();
        }
    
        function addMarker(map, event) {
            if (markerCount < 10) {
                var uid = genId();
                $(this).gmap3({
                    marker: {
                        latLng: event.latLng,
                        options: {
                            draggable: true,
                            animation: google.maps.Animation.DROP,
                            icon: iconValues,
                            shadow: shadowValues
                        },
                        events: {
                            click: function() {
                                clearMarker(uid);
                            },
                            dragend: listMarkers
                        },
                        id: uid
                    }
                });
                markerCount++;
                listMarkers();
    
            } else {
                return false;
            };
        }
        function listMarkers() {
            $(".gmap3").gmap3({
                get: {
                    all: true,
                    callback: function(results) {
                        var coords = '';
                        $("#geofenceCoords_dragndrop").empty();
    
                        $.each(results, function (i, marker) {
                            //$("#inputArray").append('{"latitude":' + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() + '},' + '<br>');
                            coords+= '  {"latitude":'  + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() +'},\n';
                        });
                        $("#geofenceCoords_dragndrop").val('['+'\n'+coords.substr(0, (coords.length-2))+'\n]'); 
                    }
                }
            });
        }
        function clearMarker(uid) {
            $('.gmap3').gmap3({
                clear: {
                    id: uid,
                    callback: function() {
                        listMarkers();
                        markerCount--;
                    }
                }
            });
        }
    
        var markerCount = 0;
    
        $(".gmap3").gmap3({
            map: {
                options: mapOpts,
                events: {
                    click: addMarker
                }
            }
        });
    
     }
    
    //////// GMAP3 ADDRESS ////////
    
    $.mapAddress = function(){
    
    
    
    var mapOpts = {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
            },
            navigationControl: true,
            scrollwheel: true,
            disableDoubleClickZoom: true,
            streetViewControl: false,
        };
    
      var iconValues =
      new google.maps.MarkerImage('http://www.mindboxdesigns.com/test-images/map_marker_default.png', //icon url
      new google.maps.Size(28.0, 43.0),
      new google.maps.Point(0, 0),
      new google.maps.Point(14.0, 43.0));
    
      var shadowValues =
      new google.maps.MarkerImage('http://www.mindboxdesigns.com/test-images/map_marker_default_shadow.png', //icon shadow url
      new google.maps.Size(50.0, 43.0),
      new google.maps.Point(0, 0),
      new google.maps.Point(14.0, 43.0)); 
    
    
        $(".gmap3").gmap3({
            map:{
            options: mapOpts
            }
    
        });
    
        setTimeout(function() {
        $('<span>').attr({ class: 'deleteIcon'}).appendTo(".gmap3");
        }, 200);
    
        $('#test-ok').click(function(){
          var addr = $('#test-address').val();
          if ( !addr || !addr.length ) return;
          $(".gmap3").gmap3({
            getlatlng:{
              address:  addr,
    
              callback: function(results){
    
                if ( !results ) return;
    
                if (markerCount < 10) {
                $(this).gmap3({
                  marker:{
    
                    latLng:results[0].geometry.location,
                    options:{
                    icon: iconValues,
                    shadow: shadowValues
                    },
                    map:{
    
                      center: true,
    
                    },
    
                  },
                  autofit:{maxZoom: 14},
    
                });
                listMarkers();
                markerCount++;
                $('#test-address').val("");
    
                }else {
                    $('#test-address').val("limit Reached");
                    $('#test-address').css('color','red');
                    $('#test-address').attr('readonly','readonly');
                return false;
            };
    
              }
            }
          });
        });
    
        function listMarkers() {
            $(".gmap3").gmap3({
                get: {
                    all: true,
                    callback: function(results) {
                        var coords = '';
                        //$("#geofenceCoords_address").val("");
    
                        $.each(results, function (i, marker) {
                            //$("#inputArray").append('{"latitude":' + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() + '},' + '<br>');
                            coords+= '  {"latitude":'  + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() +'},\n';
                        });
                        $("#geofenceCoords_address").val('['+'\n'+coords.substr(0, (coords.length-2))+'\n]');   
                    }
                }
            });
        }
    
        var markerCount = 0;
    
        $('.gmap3').on('click', '.deleteIcon', function(){                      
        //alert("Handler");
        if(markerCount <= 10){
            markerCount = 0;
        }
        $('.gmap3').gmap3('clear', 'markers');
        $("#geofenceCoords_address").val('');
        $('#test-address').val('');
        $('#test-address').css('color','black');
        $('#test-address').removeAttr('readonly');
    
        });
    
        $('#test-address').keypress(function(e){
          if (e.keyCode == 13){
            $('#test-ok').click();
          }
        });
    }
    
    //////// JSON ARRAY VALIDATION ////////
    
    
    $('#geofenceCoords_array').on('focusout keyup', function (e) {
        var fieldValue = $(this).val(),
        json;
    
         try {
        json = JSON.parse(fieldValue);
        if (json.length > 3) {
            throw new Error("E_TOO_MANY_COORD");
        }
    
        _.each(json, function (coordinate) {
            if (!_.has(coordinate, 'latitude') || !_.has(coordinate, 'longitude')) {
                throw new Error("E_INVALID_COORD");
            }
        });
    
        } catch (e) {
        console.log(e.message);
        // handle your invalid json and return to stop further execution
        if (e.message === "E_TOO_MANY_COORD") {
            $('#errorMessage').text("You cannot exeed more than 3 coordiniates");
            $('#errorMessage').removeClass().addClass('error');
            $('#show_array').removeClass().addClass('disabled');
        } else if (e.message === "E_INVALID_COORD") {
            $('#errorMessage').html("Please provide valid coordinate pairs:<br> [{\"latitude\":33.851871,\"longitude\":-84.364336}]");
            $('#errorMessage').removeClass().addClass('warning');
            $('#geofenceCoords_array').css({
                'border': '1px solid black'
            });
            $('#show_array').removeClass().addClass('disabled');
        }
    
        return;
    }
    
    $('#arrayNum').text(json.length);
    $('#errorMessage').removeClass().addClass("hide");
    $('#show_array').removeClass().addClass('enabled');
    $('#errorMessage').text("");
    $('#geofenceCoords_array').css({
        'border': '1px solid black'
    });
    
    if ($('#arrayNum').text() == 0) {
        $('#show_array').removeClass().addClass('disabled');
    }
    
    });
    
    $('#geofenceCoords_array').on('focusout mouseout', function (e) {
    
    var fieldValue = $(this).val(),
        json;
    
    if (e.which === 8) return;
    
    try {
        json = JSON.parse(fieldValue);
    } catch (e) {
        console.log(e.message);
    
        if (e instanceof SyntaxError) {
            $('#errorMessage').text("Please use valid json");
            $('#errorMessage').removeClass().addClass('error');
            $('#geofenceCoords_array').css({
                'border': '1px solid red'
            });
            $('#show_array').removeClass().addClass('disabled');
        }
    
        if (fieldValue === "") {
            $("#arrayNum").text("0");
            $('#geofenceCoords_array').css({
                'border': '1px solid black'
            });
            $('#show_array').removeClass().addClass('disabled');
            $('#errorMessage').removeClass().addClass('hide');
        }
        return;
        }
    
        });
    
    $('html,body').on('mousemove', function (e) {
    
    var fieldValue = $("#geofenceCoords_array").val(),
        json;
    
    if (e.which === 8) return;
    
    try {
        json = JSON.parse(fieldValue);
    } catch (e) {
        console.log(e.message);
    
        if (e instanceof SyntaxError) {
            $('#errorMessage').text("Please use valid json");
            $('#errorMessage').removeClass().addClass('error');
            $('#geofenceCoords_array').css({
                'border': '1px solid red'
            });
            $('#show_array').removeClass().addClass('disabled');
        }
    
        if (fieldValue === "") {
            $("#arrayNum").text("0");
            $('#geofenceCoords_array').css({
                'border': '1px solid black'
            });
            $('#show_array').removeClass().addClass('disabled');
            $('#errorMessage').removeClass().addClass('hide');
        }
        return;
        }
        });
    
    
    //////// MAP TRANSITIONS ////////
    
    $('#default_selection').prop("checked",true);
    $('#default_selection').attr("checked",true);
    
    
    $('#show_array').bind('DOMNodeInserted DOMSubtreeModified DOMNodeRemoved', function(event) {
         if($("#show_array").hasClass('enabled')){
         $.mapArray();
         }
     });
    
    
     $("[name=mapSelect]").change(function() {
        $('.gmap3').gmap3('destroy');
    
    
        if($(this).val() == 'JSONArray'){
        $('.gmap3').attr("id","newId1");
        $(".gmap3").gmap3({
            map:{options: mapOpts}
        });
        $("#geofenceCoords_dragndrop").val("");
        $("#geofenceCoords_address").val("");
        $.mapArray();
        }
    
        if($(this).val() == 'dragnDrop'){
        $('.gmap3').attr("id","newId2");
        $(".gmap3").gmap3({
            map:{options: mapOpts}
        });
        $("#geofenceCoords_array").val("");
        $("#geofenceCoords_address").val("");
        $.mapDrop();
        }
    
        if($(this).val() == 'addrSelect'){
        $('.gmap3').attr("id","newId3");
        $(".gmap3").gmap3({
            map:{options: mapOpts}
        });
        $("#geofenceCoords_array").val("");
        $("#geofenceCoords_address").val("");
        $("#geofenceCoords_dragndrop").val("");
        $.mapAddress();
        }
    
    
    });
    
    });
    

1 个答案:

答案 0 :(得分:0)

没关系,让它运转起来。

我用过: $('#test-ok').bind('click',function(){ }

而不是:$('#test-ok').click(function(){ }

然后,当我在无线电选择中点击Drag n Drop或JSON时,我只使用了$('#test-ok').unbind('click');