2017-05-31 69 views
1

我正在努力創建一個地圖,默認情況下加載地址,並顯示在搜索框中的標記和地址的地方,工作正常。但我需要添加將首先刪除所有標記然後放置標記的單擊事件。到目前爲止,我開發的腳本是我所需要的。但是,當用戶點擊地圖時,搜索框將獲取地址,但舊標記不會刪除,並且新標記不會顯示在點擊位置。谷歌地圖刪除所有標記,然後創建新

這裏我的工作示例代碼: https://jsfiddle.net/ehsLLg26/

這裏我的代碼:

 <script type="text/javascript"> 
       function initAutocomplete() {  
        var myOptions = { 
         zoom: 15, 
         mapTypeId: google.maps.MapTypeId.ROADMAP, 
         mapTypeControl: false 
        }      

        var map; 
        var marker; 
        var geocoder = new google.maps.Geocoder(); 
        var address = document.getElementById('pac-input').value; 
        var infowindow = new google.maps.InfoWindow();            

        geocoder.geocode({ address: address}, function(results, status) { 
         if (status == google.maps.GeocoderStatus.OK && results.length) { 
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) { 

           //create map 
           map = new google.maps.Map(document.getElementById("map"), myOptions); 

           //center map 
           map.setCenter(results[0].geometry.location); 

           //create marker 
           marker = new google.maps.Marker({ 
            position: results[0].geometry.location, 
            map: map, 
            title: document.getElementById('pac-input').value, 
           });                  

           // Create the search box and link it to the UI element. 
           var input = document.getElementById('pac-input'); 
           var searchBox = new google.maps.places.SearchBox(input); 
           map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); 

           // Bias the SearchBox results towards current maps viewport. 
           map.addListener('bounds_changed', function() { 
            searchBox.setBounds(map.getBounds()); 
           }); 

           var markers = []; 
           // Listen for the event fired when the user selects a prediction and retrieve 
           // more details for that place. 
           searchBox.addListener('places_changed', function() { 
            var places = searchBox.getPlaces(); 

            if (places.length == 0) { 
             return; 
            }  

            // Clear out the old markers. 
            markers.forEach(function(marker) { 
             marker.setMap(null); 
            }); 
            marker.setMap(null); 
            markers = []; 

            // For each place, get the icon, name and location. 
            var bounds = new google.maps.LatLngBounds(); 
            places.forEach(function(place) { 
             var icon = { 
              url: place.icon, 
              size: new google.maps.Size(71, 71), 
              origin: new google.maps.Point(0, 0), 
              anchor: new google.maps.Point(17, 34), 
              scaledSize: new google.maps.Size(25, 25) 
             }; 

             // Create a marker for each place. 
             markers.push(new google.maps.Marker({ 
              map: map, 
              title: place.name, 
              position: place.geometry.location 
             })); 

             if (place.geometry.viewport) { 
              // Only geocodes have viewport. 
              bounds.union(place.geometry.viewport); 
             } else { 
              bounds.extend(place.geometry.location); 
             } 
             }); 
            map.fitBounds(bounds); 
           });          

           google.maps.event.addListener(map, 'click', function(event) { 
            geocoder.geocode({ 
             'latLng': event.latLng 
             }, function(results, status) { 
              if (status == google.maps.GeocoderStatus.OK) { 
               if (results[0]) { 
                document.getElementById('pac-input').value = results[0].formatted_address;              
               } 
              } 
             });            
            placeMarker(event.latLng); 
           });                           

           function placeMarker(location) {           
            if (marker) {            
             marker.setPosition(location);           
            } else { 
             marker = new google.maps.Marker({ 
              position: place.geometry.location, 
              map: map, 
              title: place.name, 
             }); 
            } 
           }          
          } 
         } 
         else { 
          $('#map').css({'height' : '15px'}); 
          $('#map').html("Oops! address could not be found, please make sure the address is correct."); 
          resizeIframe(); 
         } 
        });       

        function resizeIframe() { 
         var me = window.name; 
         if (me) { 
          var iframes = parent.document.getElementsByName(me); 
          if (iframes && iframes.length == 1) { 
           height = document.body.offsetHeight; 
           iframes[0].style.height = height + "px"; 
          } 
         } 
        } 
        } 
       </script> 

如何重現問題:1. 運行腳本 2.在搜索框中輸入任意地址,然後點擊進入 3.標記添加後,點擊附近的位置 結果:舊標誌不會被刪除,新的標誌不顯示。 預期結果:舊標記刪除並出現新標記。

+0

//清除出單擊事件 –

+0

裏面的舊標誌從小提琴刪除您的鑰匙! –

+0

@Dinesh,添加marker.setMap(null);到功能placeMarker不起作用。 – Viktor

回答

2

你需要改變:

 // Clear out the old markers. 
     markers.forEach(function(marker) { 
      marker.setMap(null); 
     }); 
     marker.setMap(null); 
     markers = []; 

// Clear out the old markers. 
    markers.forEach(function(marker) { 
     marker.setMap(null); 
    }); 

,並google.maps.event.addListener(map, 'click', function(event) {

google.maps.event.addListener(map, 'click', function(event) { 
     geocoder.geocode({ 
     'latLng': event.latLng 
     }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (results[0]) { 
      markers.forEach(function(marker) { 
       marker.setMap(null); 
      }) 
      document.getElementById('pac-input').value = results[0].formatted_address; 
      } 
     } 
     }); 
     placeMarker(event.latLng); 
    }); 

編輯:

替換:

// Create a marker for each place. 
    markers.push(new google.maps.Marker({ 
     map: map, 
     title: place.name, 
     position: place.geometry.location 
})); 

有:

placeMarker(place.geometry.location) 

的jsfiddle:

function initAutocomplete() { 
 
    var myOptions = { 
 
    zoom: 5, 
 
    mapTypeId: google.maps.MapTypeId.ROADMAP, 
 
    mapTypeControl: false 
 
    } 
 

 
    var map; 
 
    var marker; 
 
    var geocoder = new google.maps.Geocoder(); 
 
    var address = document.getElementById('pac-input').value; 
 
    var infowindow = new google.maps.InfoWindow(); 
 
    var markers = []; 
 

 
    geocoder.geocode({ 
 
    address: address 
 
    }, function(results, status) { 
 
    if (status == google.maps.GeocoderStatus.OK && results.length) { 
 
     if (status != google.maps.GeocoderStatus.ZERO_RESULTS) { 
 

 
     //create map 
 
     map = new google.maps.Map(document.getElementById("map"), myOptions); 
 

 
     //center map 
 
     map.setCenter(results[0].geometry.location); 
 

 
     //create marker 
 
     marker = new google.maps.Marker({ 
 
      position: results[0].geometry.location, 
 
      map: map, 
 
      title: document.getElementById('pac-input').value, 
 
     }); 
 

 
     // Create the search box and link it to the UI element. 
 
     var input = document.getElementById('pac-input'); 
 
     var searchBox = new google.maps.places.SearchBox(input); 
 
     map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); 
 

 
     // Bias the SearchBox results towards current maps viewport. 
 
     map.addListener('bounds_changed', function() { 
 
      searchBox.setBounds(map.getBounds()); 
 
     }); 
 

 
     
 
     // Listen for the event fired when the user selects a prediction and retrieve 
 
     // more details for that place. 
 
     searchBox.addListener('places_changed', function() { 
 
      var places = searchBox.getPlaces(); 
 

 
      if (places.length == 0) { 
 
      return; 
 
      } 
 

 
      // Clear out the old markers. 
 
      markers.forEach(function(marker) { 
 
      marker.setMap(null); 
 
      }); 
 

 
      // For each place, get the icon, name and location. 
 
      var bounds = new google.maps.LatLngBounds(); 
 
      places.forEach(function(place) { 
 
      var icon = { 
 
       url: place.icon, 
 
       size: new google.maps.Size(71, 71), 
 
       origin: new google.maps.Point(0, 0), 
 
       anchor: new google.maps.Point(17, 34), 
 
       scaledSize: new google.maps.Size(25, 25) 
 
      }; 
 
\t \t \t \t \t \t \t placeMarker(place.geometry.location) 
 
      if (place.geometry.viewport) { 
 
       // Only geocodes have viewport. 
 
       bounds.union(place.geometry.viewport); 
 
      } else { 
 
       bounds.extend(place.geometry.location); 
 
      } 
 
      }); 
 
      map.fitBounds(bounds); 
 
     }); 
 

 
     google.maps.event.addListener(map, 'click', function(event) { 
 
      geocoder.geocode({ 
 
      'latLng': event.latLng 
 
      }, function(results, status) { 
 
      if (status == google.maps.GeocoderStatus.OK) { 
 
       if (results[0]) { 
 
       markers.forEach(function(marker) { 
 
        marker.setMap(null); 
 
       }); 
 
       document.getElementById('pac-input').value = results[0].formatted_address; 
 
          placeMarker(event.latLng); 
 
       } 
 
      } 
 
      }); 
 
     }); 
 

 
     function placeMarker(location) { 
 
      if (marker) { 
 
      marker.setPosition(location); 
 
      } else { 
 
      marker = new google.maps.Marker({ 
 
       position: place.geometry.location, 
 
       map: map, 
 
       title: place.name, 
 
      }); 
 
      } 
 
     } 
 
     } 
 
    } else { 
 
     $('#map').css({ 
 
     'height': '15px' 
 
     }); 
 
     $('#map').html("Oops! address could not be found, please make sure the address is correct."); 
 
     resizeIframe(); 
 
    } 
 
    }); 
 

 
    function resizeIframe() { 
 
    var me = window.name; 
 
    if (me) { 
 
     var iframes = parent.document.getElementsByName(me); 
 
     if (iframes && iframes.length == 1) { 
 
     height = document.body.offsetHeight; 
 
     iframes[0].style.height = height + "px"; 
 
     } 
 
    } 
 
    } 
 
}
/* Always set the map height explicitly to define the size of the div 
 
* element that contains the map. */ 
 

 
#map { 
 
    height: 100%; 
 
} 
 

 

 
/* Optional: Makes the sample page fill the window. */ 
 

 
html, 
 
body { 
 
    height: 100%; 
 
    margin: 0; 
 
    padding: 0; 
 
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box"> 
 
<div id="map"></div> 
 
<!-- Replace the value of the key parameter with your own API key. --> 
 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBZbI5EJHVyNPd07tdhGgIODBpuqCePlIw&libraries=places&callback=initAutocomplete"> 
 

 

 
</script>

+0

縮小並在搜索過程中檢查,舊標記與新標記保持一致 –

+0

是的,我固定了他問的任何問題創造更多! DOH! –

+0

但最後他的帖子,OP提到_Expected結果:老標記刪除和新的標記appear._ –