简体   繁体   English

使用 jQuery ajax 定期在谷歌地图上映射标记

[英]Map markers on google maps periodically using jQuery ajax

I am attempting to populate a google map with a marker periodically.我试图定期用标记填充谷歌地图。 I have an ajax request that fetches a single latitude and longitude co-ordinate and I want it to place this on a map however I am having no luck in doing so.我有一个获取单个纬度和经度坐标的 ajax 请求,我希望它把它放在地图上,但是我没有这样做。

I can wrap the whole thing in setInterval but this refreshes the whole map which I would prefer not to do due to the "flash".我可以将整个内容包装在 setInterval 中,但这会刷新整个地图,由于“闪光”,我不想这样做。

HTML HTML

<div id="map"></div>

JS JS

function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 5,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: {lat: 53.810879, lng: -1.740658}
        });

        setInterval(function(map) {
            $.ajax({
                type: "get",
                url: "URL TO REQUEST",
                success:function(data, map)
                {
                    var lat = parseFloat(data.lat);
                    var lng = parseFloat(data.lng);
                    var marker = new google.maps.Marker({
                      position: new google.maps.LatLng(lat,lng),
                      setMap: map,

                    });
                }
            });
        }, 10000);
 }

Any help would be appreciated.任何帮助,将不胜感激。

You have two issues:你有两个问题:

  1. setMap is not a valid MarkerOption setMap不是有效的MarkerOption
  2. the setInterval function doesn't get passed a useful argument. setInterval函数没有传递有用的参数。

proof of concept fiddle概念证明小提琴

code snippet:代码片段:

 var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP, center: { lat: 53.810879, lng: -1.740658 } }); setInterval(function() { $.ajax({ type: "get", url: "https://staging.yorkshiredalesthepolarexpressride.com/wp-json/pedash/v1/dashboard/tickets", success: function(data, map1) { console.log(data); var lat = parseFloat(data.lat); var lng = parseFloat(data.lng); var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), map: map }); } }); }, 10000); }
 /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="map"></div> <!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=geometry"> </script>

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

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