javascript - 只更新折线而不是整个 map

标签 javascript c# asp.net-mvc google-maps setinterval

我正在尝试创建一个 ASP.NET 页面,可以使用 Google Maps API 跟踪当前用户的路线。问题是每当我使用间隔来绘制折线时,整个 Google map 都会刷新,从而导致页面闪烁。

这是我的代码:

 <script>
    //declare variables
    var interval;
    var coordinates = [];
    var x = document.getElementById("exception");

    //Get current position and loop this
    function getLocation() {
        //Check if the user has a geolocation
        if (navigator.geolocation) {
            interval = setInterval(function () { navigator.geolocation.getCurrentPosition(showPosition); }, 500);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    //Get the latitude and longitude and draw a polylin
    function showPosition(position) {
        console.log(position.coords.latitude + " " + position.coords.longitude);

        //Map options for the Google map and center the current position
        var mapOptions = {
            zoom: 15,
            center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
        }

        //Add the options to the google map and display it
        var map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);

        //Create a marker for the current position
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
            title: "Current position!"
        });

        // To add the marker to the map, call setMap();
        marker.setMap(map);

        //Add the current coordinates to the array
        coordinates.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

        //Create a polyline with the coordinates array
        var flightPath = new google.maps.Polyline({
            path: coordinates,
            geodesic: true,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2
        });

        //To add the polylin to the map, call setMap();
        flightPath.setMap(map);
    }

    //Stop the interval
    $("#stop").click(function () {
        clearInterval(interval);
        coordinates = [];
    });
</script>

提前致谢, 布伦特原油

最佳答案

map 闪烁是因为您每次运行 showPosition 时都在重新创建它。您应该将 map 变量设置为全局变量,并且仅在页面加载时设置一次。同样,您应该将标记和flightPath变量设置为全局变量,并确保在使用marker.setMap(null)和flightPath.setMap(null)重新创建它们之前将它们从 map 中删除,或者更好的是用新位置更新它们信息。

关于javascript - 只更新折线而不是整个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29279042/

相关文章:

javascript - 访问 Javascript JSON 对象

javascript - 如何使用填充的输入值获取当前网站的html源

c# - 如何在自定义 SSIS 组件中创建目标列?

c# - 如何使用 C# .net Core 执行 git 命令显式给出存储库路径?

asp.net-mvc - ASP.NET OmniSharp 服务器未在 Ubuntu Mono 上运行

c# - 两个不同的 Controller 可以访问 mvc 中的单个 View 吗?

javascript - Chrome 中的 ScrollIntoView

javascript - 输入字段模糊事件不会在 iPad 键盘隐藏上触发?

C# 字典包含Key

c# - 将服务引用传递给另一个服务层是不好的做法吗?