简体   繁体   English

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

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

I am writing this question, having previously searched quite a lot for this question, but haven't found a thread that I can use for my current problem.我正在写这个问题,之前已经为这个问题搜索了很多,但还没有找到可用于我当前问题的线程。 (Probably due to lack of skill). (可能是由于缺乏技能)。 If there is a question that addresses exactly this, please redirect me to it!如果有一个问题恰好解决了这个问题,请将我重定向到它!

I am creating a PWA that uses google maps for user interaction, the idea being that a user can place a marker on said map by either:我正在创建一个使用谷歌地图进行用户交互的 PWA,其想法是用户可以通过以下任一方式在所述 map 上放置一个标记:

  1. Clicking the map on the desired location在所需位置单击 map
  2. Clicking a button that places a marker on the user's current location单击在用户当前位置放置标记的按钮
  3. Writing the address (geocoding)写入地址(地理编码)

For now, I have a code that permits me doing the first two actions.现在,我有一个代码允许我执行前两个操作。 In both functions, I have an IF, that tries to overwrite any existing markers, so as to only have a maximum of one marker on the map. (Ignore geocoding remark, it hasn't been implemented yet)在这两个函数中,我都有一个 IF,它试图覆盖任何现有的标记,以便在 map 上最多只有一个标记。(忽略地理编码注释,它尚未实现)

I come across the following problem: Whilst if the user clicks the map, and then clicks the geolocating button, the first marker is removed.我遇到以下问题:如果用户单击 map,然后单击地理定位按钮,第一个标记将被删除。 (Desired outcome) (期望的结果)

  • If the user clicks the geolocating button, and then clicks the map, no marker is removed.如果用户单击地理定位按钮,然后单击 map,则不会删除任何标记。

I can't get a working HTML/CSS/Javascript snippet to work, as it requires hiding the google maps key, and that exceeds my capabilities.我无法使有效的 HTML/CSS/Javascript 代码片段正常工作,因为它需要隐藏谷歌地图键,这超出了我的能力范围。 But I think that the problem(s) lie in my Javascript code:但我认为问题出在我的 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);

Clarification: marker2 is the interactive marker that users create through the 3 actions stated.说明: marker2是用户通过上述 3 个动作创建的交互式标记。 marker is just a blue dot that appears automatically on user's current location if the function onSuccessGeolocating gets approved.如果 function onSuccessGeolocating获得批准,标记只是一个自动出现在用户当前位置的蓝点。

I know there are a lot of google.maps.Marker related questions, and I have really tried resolving this on my own (setting marker2 as global variable, trying to set map's markers to null before the functions..) but have gotten nowhere.我知道有很多与 google.maps.Marker 相关的问题,我真的尝试过自己解决这个问题(将 marker2 设置为全局变量,尝试在函数之前将地图的标记设置为 null ..)但没有任何进展。

Thank you very much, and sorry for possibly confusing code lines.非常感谢,对于可能混淆的代码行,我们深表歉意。

The issue is that you create new markers, but you don't reference back to it in placeMarker when you want to replace the position later on.问题是您创建了新标记,但是当您稍后想要替换 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);

Side-note: in the URL in your <script> tag, you should have a callback search parameter (usually callback=oninit ), Google's script will call this through window.oninit when it's been loaded, so I'd replace your window event listener with:旁注:在您的<script>标签中的 URL 中,您应该有一个callback搜索参数(通常是callback=oninit ),谷歌的脚本将在加载时通过window.oninit调用它,所以我将替换您的 window 事件听众:

window.oninit = initialize2;

The issue is that you create a new variable (marker) that holds the newly created marker, but you don't reference back to it in placeMarker when you want to replace the position later on.问题是您创建了一个新变量(标记)来保存新创建的标记,但是当您稍后想要替换 position 时,您没有在 placeMarker 中引用它。

I've changed your placeMarker function to take a type argument which is null or "circle" to be able to change the marker2 instance options without redundant code.我已经将您的 placeMarker function 更改为采用类型参数 null 或“circle”,以便能够在没有冗余代码的情况下更改 marker2 实例选项。 There's a lot of code that needs improvement but this will achieve your desired outcome.有很多代码需要改进,但这将达到您想要的结果。

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

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