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