2017-05-31 11 views
-1

郵便番号のある場所を検索すると、郵便番号と一緒にGoogleマップを中心にしてマーカーを追加します。私は新しい検索をするときに古いマーカーを削除します。googlemap api v3でマーカーを1つ削除する

 $('body').on('blur', '#CodePostalA', function(){ 

     var zipcode = $('#CodePostalA').val(); 
     var $this = $(this); 
     var geocoder = new google.maps.Geocoder; 

      geocoder.geocode({'address': zipcode}, function(results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        map.setCenter(results[0].geometry.location); 
        map.setZoom(20); 

       } 

       if ($('#adresse').length > 0) { 
        newMarker = new google.maps.Marker({ 
         position: results[0].geometry.location, 
         map: map, 
         icon: new google.maps.MarkerImage(
          'images/marker-new.png', 
          null, 
          null, 
          null, 
          new google.maps.Size(36, 36) 
         ), 
         draggable: true, 

         animation: google.maps.Animation.DROP, 
        }); 



        google.maps.event.addListener(newMarker, "mouseup", function(event) { 
         var latitude = this.position.lat(); 
         var longitude = this.position.lng(); 


         geocoder.geocode({'location': this.position}, function(results, status) { 
          if (status === google.maps.GeocoderStatus.OK) { 
           if (results[1]) { 
            $('#adresse').val(results[0].formatted_address); 
           } else { 
            console.log('Aucun résulat trouvé'); 
           } 
          } else { 
           console.log('Echec géolocation: ' + status); 
          } 
         }); 
        }); 

       } 




      }); 



    }); 



    addMarkers(props, map); 
}, 300); 
+0

newMarker.setMap(null);新しいマーカーを作成する前にこれを試してください –

+0

私は理解しますが、newMarker = new google.maps.Marker({})の前にnewMarker.setMapを追加すると、私のコンソールにエラーがあります=> Uncaught TypeError:newMarker.setMapは関数ではありません – phpnewbie

+0

[Google Maps APIを使用したジオコーディング]の複製 - 別のマーカーを追加するのではなく、既存のマーカーを更新する](https://stackoverflow.com/questions/12628994/geocoding-with-google-maps-api-updating-existing-marker-rather-than- add-ano) – geocodezip

答えて

0

は、変数を使用してマーカーを追跡し、それはそれを削除するための時間であるとき、marker.setMap(null)をマップから削除します。

すべての参照が削除されると、古いマーカーオブジェクトがシーンの後ろでガベージコレクションされます。

また、毎回新しいマーカーオブジェクトを作成するのではなく、マーカーオブジェクトを再利用することもできます。

関連する問題