javascript - 通过切换 div 标签在 Google map 中添加/删除标记

标签 javascript html css google-maps

我正在构建一个带有 map (谷歌地图)组件的移动网络应用程序。
我正在尝试创建一个切换 onclick="gas()"这将根据关键字(gas)向 map 添加(然后删除)标记,这样当有人开车四处寻找加油站时,他们可以单击 gas 图标并将加油站添加到 map 。 除拆卸部分外,一切正常。我无法使切换的第二部分正常工作,即从 map 中删除标记。我相信我在这里遗漏了一些简单的东西但无法弄清楚(我认为它是 else 部分,特别是 clearMarkers() 函数。任何帮助将不胜感激。

顺便说一句,我是一个初学者 JS 程序员,根本没有接受过任何培训,并且使用了来自网络的代码混搭。 这是代码。

Javascript:

//Gas
var gas_markers = null;
function gas() {
if (gas_markers == null) {
    document.getElementById('gas').style.backgroundColor = "rgb(175,175,175)";
    document.getElementById('gas').style.borderColor = "black";
    document.getElementById('gas').style.color = "rgb(75,75,75)";

    var request = {
        location: arena,
        radius: 3500,
        keyword: ["gas"]
  };
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);


function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
  createMarker(results[i]);
    }
  }
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    var gas_markers = new MarkerWithLabel({
    position: place.geometry.location,
    draggable: false,
    raiseOnDrag: false,
    map: map,
    icon: "images/gas1.png",
    labelContent: "",
    labelAnchor: new google.maps.Point(10, 0),
    labelClass: "pin", // the CSS class for the label
    labelStyle: {opacity: 0.95}
    });

    var infowindow = new google.maps.InfoWindow();

  google.maps.event.addListener(gas_markers, 'click', function() {
    infowindow.setContent('Promo Code:<br>Gas');
    infowindow.open(map, this);
  });
}
 gas_markers = 'one';

 } 
else

{       
    function clearMarkers() {
        callback(null);
        gas_markers = [];

                        } 

    document.getElementById('gas').style.backgroundColor = "rgb(75,75,75)";
    document.getElementById('gas').style.borderColor = "gray";
    document.getElementById('gas').style.color = "rgb(175,175,175)";  

    gas_markers = null;
    }       

} 
 //Gas - end

HTML:

<div onclick="gas()" id="gas"><div class="label-map">Gas</div></div>

感谢您的帮助!

最佳答案

  1. 创建一个全局数组来保存标记 (gas_markers)
  2. 修改您的 clearMarkers 函数以处理该数组,在删除之前从 map 中移除标记:

    函数 clearMarkers() {

    for (var i = 0; i < gas_markers.length; i++) {
        gas_markers[i].setMap(null);
    }
    gas_markers = [];
    

工作代码片段:

var geocoder;
var map;

function initialize() {
    map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
}
google.maps.event.addDomListener(window, "load", initialize);

//Gas
var gas_markers = null;

function gas() {
    if (gas_markers === null) {
        document.getElementById('gas').style.backgroundColor = "rgb(175,175,175)";
        document.getElementById('gas').style.borderColor = "black";
        document.getElementById('gas').style.color = "rgb(75,75,75)";

        var request = {
            location: map.getCenter(),
            radius: 3500,
            keyword: ["gas"]
        };
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(request, callback);


        function callback(results, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                if (gas_markers === null) gas_markers = [];
                for (var i = 0; i < results.length; i++) {
                    createMarker(results[i]);
                }
            }
        }

        function createMarker(place) {
            var placeLoc = place.geometry.location;
            var gas_marker = new MarkerWithLabel({
                position: place.geometry.location,
                draggable: false,
                raiseOnDrag: false,
                map: map,
                // icon: "images/gas1.png",
                labelContent: "",
                labelAnchor: new google.maps.Point(10, 0),
                labelClass: "pin", // the CSS class for the label
                labelStyle: {
                    opacity: 0.95
                }
            });
            gas_markers.push(gas_marker);
            var infowindow = new google.maps.InfoWindow();

            google.maps.event.addListener(gas_marker, 'click', function () {
                infowindow.setContent('Promo Code: <br> Gas');
                infowindow.open(map, this);
            });
        }
        // gas_markers = 'one';

    } else {

        clearMarkers();
        document.getElementById('gas').style.backgroundColor = "rgb(75,75,75)";
        document.getElementById('gas').style.borderColor = "gray";
        document.getElementById('gas').style.color = "rgb(175,175,175)";

        gas_markers = null;

    }

    function clearMarkers() {

        for (var i = 0; i < gas_markers.length; i++) {
            gas_markers[i].setMap(null);
        }
        gas_markers = [];
    }

}
//Gas - end
html, body, #map_canvas {
    height: 500px;
    width: 500px;
    margin: 0px;
    padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
<div onclick="gas()" id="gas">
    <div class="label-map">Gas</div>
</div>

关于javascript - 通过切换 div 标签在 Google map 中添加/删除标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26258125/

相关文章:

javascript - 在表单提交之前获取单选按钮的值

javascript - 让 php 变量与嵌入的 javascript 函数一起使用

javascript - 代码学校的最佳位置

html - 使用 XSLT 交替行颜色,使用 `rowspan` 交替单元格

带有水平滚动条的 HTML 内表

javascript - Fullcalendar 3 - 当前日期边框颜色

javascript - 使用 Jasmine 测试 Angular Promise

html - 如何为响应式网站创建带滚动条的固定背景?

css - Firefox 默认字体大小问题

jquery - 使用 jQuery.css 在 Internet Explorer 中获取值