繁体   English   中英

如何设置 map 一次只保存一个标记,用两个单独的函数创建标记?

[英]How to set map to only hold one marker at a time, with two separate functions creating markers?

我正在写这个问题,之前已经为这个问题搜索了很多,但还没有找到可用于我当前问题的线程。 (可能是由于缺乏技能)。 如果有一个问题恰好解决了这个问题,请将我重定向到它!

我正在创建一个使用谷歌地图进行用户交互的 PWA,其想法是用户可以通过以下任一方式在所述 map 上放置一个标记:

  1. 在所需位置单击 map
  2. 单击在用户当前位置放置标记的按钮
  3. 写入地址(地理编码)

现在,我有一个代码允许我执行前两个操作。 在这两个函数中,我都有一个 IF,它试图覆盖任何现有的标记,以便在 map 上最多只有一个标记。(忽略地理编码注释,它尚未实现)

我遇到以下问题:如果用户单击 map,然后单击地理定位按钮,第一个标记将被删除。 (期望的结果)

  • 如果用户单击地理定位按钮,然后单击 map,则不会删除任何标记。

我无法使有效的 HTML/CSS/Javascript 代码片段正常工作,因为它需要隐藏谷歌地图键,这超出了我的能力范围。 但我认为问题出在我的 Javascript 代码中:

var map2;
var marker2;
function initialize2() {

    google.maps.controlStyle = 'azteca';
    var mapOptions2 = {
        zoom: 15,
        minZoom: 12,
        maxZoom:19,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: false,
        gestureHandling: "greedy",

        center: new google.maps.LatLng(41.727751, 1.827424),
        restriction: {
            latLngBounds: {
              north: 41.753,
              south: 41.715,
              east: 1.857,
              west: 1.806,
            },
          },
        
        styles: [{ // VISIBLE BARS RESTAURANTS
            featureType: "poi",
            stylers: [{ visibility: "off" }],
        }, {
            featureType: "poi.park",
            stylers: [{ visibility: "on" }],
        }, {
            featureType: "poi.park",
            elementType: "labels",
            stylers: [{ visibility: "off" }],
        }, {
            featureType: "transit",
            stylers: [{ visibility: "off" }],
        }]
    };
    
    
    
    map2 = new google.maps.Map(document.getElementById('map-canvas-inseg'), mapOptions2);

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onSuccessGeolocating);
        
    }
 

// Add marker when map is clicked (and overwrite when it is clicked again)
   

    google.maps.event.addListener(map2, 'click', function(event) {
        placeMarker(event.latLng);
    });

    function placeMarker(location) {

        if (marker2 == null)
            {
                marker2 = new google.maps.Marker({
                position: location,
                map: map2
                }); 
            } 
        else
            {
                marker2.setPosition(location); 
            } 

    }

    
    
    
    function onSuccessGeolocating(position) {

        var circleBigOpt = {
            center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude), 
            map: map2,
            radius: position.coords.accuracy,
            fillColor:"#4285f4",
            fillOpacity:0.1,
            strokeWeight:0
        };
    
        var circleBig = new google.maps.Circle(circleBigOpt);
    
    
            
    
        var positionMarkerOptions = {
            position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 10,
                fillColor: '#4285f4',
                fillOpacity: 1,
                strokeColor: '#ffffff',
                strokeWeight: 1
            },
            map: map2
            };
    
        var marker = new google.maps.Marker(positionMarkerOptions);

        map2.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
    
        // Function that adds marker on the user's current location, when button "boto-marcarMapa" is clicked
        

    
        document.getElementById("boto-marcarMapa").addEventListener("click", function( event ) {
            
           if (marker2 == null) 
            { 
                marker2 = new google.maps.Marker({
                position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
                map: map2
            });
            }
            else 
            {
                //marker2.setPosition(position);
                marker2 = new google.maps.Marker({
                    position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
                    map: map2
                });
            }

            //marker2.setMap(null);
            
        });
    
    }





}
window.addEventListener('load', initialize2);

说明: marker2是用户通过上述 3 个动作创建的交互式标记。 如果 function onSuccessGeolocating获得批准,标记只是一个自动出现在用户当前位置的蓝点。

我知道有很多与 google.maps.Marker 相关的问题,我真的尝试过自己解决这个问题(将 marker2 设置为全局变量,尝试在函数之前将地图的标记设置为 null ..)但没有任何进展。

非常感谢,对于可能混淆的代码行,我们深表歉意。

问题是您创建了新标记,但是当您稍后想要替换 position 时,您没有在placeMarker中引用它。

var map2;
var marker2;

function initialize2() {

    google.maps.controlStyle = 'azteca';
    var mapOptions2 = {
        zoom: 15,
        minZoom: 12,
        maxZoom:19,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: false,
        gestureHandling: "greedy",

        center: new google.maps.LatLng(41.727751, 1.827424),
        restriction: {
            latLngBounds: {
              north: 41.753,
              south: 41.715,
              east: 1.857,
              west: 1.806,
            },
          },
        
        styles: [{ // VISIBLE BARS RESTAURANTS
            featureType: "poi",
            stylers: [{ visibility: "off" }],
        }, {
            featureType: "poi.park",
            stylers: [{ visibility: "on" }],
        }, {
            featureType: "poi.park",
            elementType: "labels",
            stylers: [{ visibility: "off" }],
        }, {
            featureType: "transit",
            stylers: [{ visibility: "off" }],
        }]
    };
    
    
    
    map2 = new google.maps.Map(document.getElementById('map-canvas-inseg'), mapOptions2);

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(onSuccessGeolocating);
    }
 

// Add marker when map is clicked (and overwrite when it is clicked again)
   

    google.maps.event.addListener(map2, 'click', function(event) {
        placeMarker(event.latLng);
    });

    function placeMarker(location) {
        if (marker2 == null)
        {
            marker2 = new google.maps.Marker({
                position: location,
                map: map2
            }); 
        } 
        else
        {
            marker2.setPosition(location); 
        } 
    }

    
    
    
    function onSuccessGeolocating(position) {

        var circleBigOpt = {
            center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude), 
            map: map2,
            radius: position.coords.accuracy,
            fillColor:"#4285f4",
            fillOpacity:0.1,
            strokeWeight:0
        };
    
        var circleBig = new google.maps.Circle(circleBigOpt);

        new google.maps.Marker({
            position: location,
            icon: {
                path: google.maps.SymbolPath.CIRCLE,
                scale: 10,
                fillColor: '#4285f4',
                fillOpacity: 1,
                strokeColor: '#ffffff',
                strokeWeight: 1
            },
            map: map2
        });

        map2.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
    
        // Function that adds marker on the user's current location, when button "boto-marcarMapa" is clicked
        

    
        document.getElementById("boto-marcarMapa").addEventListener("click", function( event ) {
            
            placeMarker(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));


            //marker2.setMap(null);
            
        });
    
    }





}
window.addEventListener('load', initialize2);

旁注:在您的<script>标签中的 URL 中,您应该有一个callback搜索参数(通常是callback=oninit ),谷歌的脚本将在加载时通过window.oninit调用它,所以我将替换您的 window 事件听众:

window.oninit = initialize2;

问题是您创建了一个新变量(标记)来保存新创建的标记,但是当您稍后想要替换 position 时,您没有在 placeMarker 中引用它。

我已经将您的 placeMarker function 更改为采用类型参数 null 或“circle”,以便能够在没有冗余代码的情况下更改 marker2 实例选项。 有很多代码需要改进,但这将达到您想要的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM