Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 谷歌地图删除所有标记,然后创建新标记_Javascript_Google Maps_Google Maps Api 3_Marker - Fatal编程技术网

Javascript 谷歌地图删除所有标记,然后创建新标记

Javascript 谷歌地图删除所有标记,然后创建新标记,javascript,google-maps,google-maps-api-3,marker,Javascript,Google Maps,Google Maps Api 3,Marker,我正在创建一个地图,默认情况下加载地址,并在搜索框中显示标记和地点地址,效果很好。但是我需要添加click事件,它将首先删除所有标记,然后放置标记。到目前为止,我正在开发的脚本,做所有我需要的。但当用户单击地图时,搜索框会获得地点地址,但旧标记不会删除,新标记不会出现在单击位置 下面是我的工作示例代码: 这是我的代码: <script type="text/javascript"> function initAutocomplete(

我正在创建一个地图,默认情况下加载地址,并在搜索框中显示标记和地点地址,效果很好。但是我需要添加click事件,它将首先删除所有标记,然后放置标记。到目前为止,我正在开发的脚本,做所有我需要的。但当用户单击地图时,搜索框会获得地点地址,但旧标记不会删除,新标记不会出现在单击位置

下面是我的工作示例代码:

这是我的代码:

        <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>

函数initAutocomplete(){
变量myOptions={
缩放:15,
mapTypeId:google.maps.mapTypeId.ROADMAP,
mapTypeControl:false
}                       
var映射;
var标记;
var geocoder=new google.maps.geocoder();
var address=document.getElementById('pac-input')。值;
var infowindow=new google.maps.infowindow();
geocoder.geocode({address:address},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK&&results.length){
if(status!=google.maps.GeocoderStatus.ZERO\u结果){
//创建地图
map=新的google.maps.map(document.getElementById(“map”),myOptions);
//中心地图
map.setCenter(结果[0].geometry.location);
//创建标记
marker=新的google.maps.marker({
位置:结果[0]。geometry.location,
地图:地图,
标题:document.getElementById('pac-input')。值,
});                                                                       
//创建搜索框并将其链接到UI元素。
var input=document.getElementById('pac-input');
var searchBox=newgoogle.maps.places.searchBox(输入);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(输入);
//将搜索框结果偏向“当前贴图”视口。
addListener('bounds_changed',function(){
searchBox.setBounds(map.getBounds());
});
var标记=[];
//侦听用户选择预测并检索时激发的事件
//关于那个地方的更多细节。
searchBox.addListener('places\u changed',function(){
var places=searchBox.getPlaces();
如果(places.length==0){
返回;
}    
//清除旧的标记。
markers.forEach(函数(marker){
marker.setMap(空);
});
marker.setMap(空);
标记=[];
//对于每个位置,获取图标、名称和位置。
var bounds=new google.maps.LatLngBounds();
地点。forEach(功能(地点){
变量图标={
url:place.icon,
大小:新谷歌地图大小(71,71),
来源:新google.maps.Point(0,0),
主播:新google.maps.Point(17,34),
scaledSize:new google.maps.Size(25,25)
};
//为每个地方创建一个标记。
markers.push(新的google.maps.Marker)({
地图:地图,
标题:place.name,
位置:place.geometry.location
}));
if(place.geometry.viewport){
//只有地理代码具有视口。
联合(place.geometry.viewport);
}否则{
扩展(place.geometry.location);
}
});
映射边界(bounds);
});                                    
google.maps.event.addListener(映射,'click',函数(事件){
地理编码({
“latLng”:event.latLng
},功能(结果、状态){
if(status==google.maps.GeocoderStatus.OK){
如果(结果[0]){
document.getElementById('pac-input')。值=结果[0]。格式化的\u地址;
}
      // 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) {
      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)