只有谷歌地图V3自动刷新标记 [英] Google Map v3 auto refresh Markers only

查看:351
本文介绍了只有谷歌地图V3自动刷新标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用谷歌地图V3显示一些引脚。我希望能够刷新标记,而不会影响你在哪里的地图或缩放级别上。我想标记将每x秒更新。

I'm using Google Maps V3 to display some pins. I want to be able to refresh markers without affecting where you're at on the map or the zoom level. I want the markers to be updated every x seconds.

我怎么会去这样做呢?我没有使用jQuery / AJAX那么多的经验。

How would I go about doing this? I don't have that much experience with jQuery/ajax.

我的地图工作示例如下。

A working example of my map is below.

http://jsfiddle.net/dLWNc/

 var locations = [
  ['some random info here', -37.8139, 144.9634, 1],
  ['some random info here', 46.0553, 14.5144, 2],
  ['some random info here', -33.7333, 151.0833, 3],
  ['some random info here', 27.9798, -81.731, 4],    ];


var map = new google.maps.Map(document.getElementById('map_2385853'), {
  zoom: 1,
  maxZoom: 8, 
  minZoom: 1, 
  streetViewControl: false,
  center: new google.maps.LatLng(40, 0),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

感谢您

推荐答案

好了,我已经得到的东西的工作 - 主要是对原来的code沉重的重构 - 你会识别各种块

OK, I've got something working - largely a heavy refactoring of your original code - you will recognize various chunks.

$(function() {
    var locations = {};//A repository for markers (and the data from which they were constructed).

    //initial dataset for markers
    var locs = {
        1: { info:'11111. Some random info here', lat:-37.8139, lng:144.9634 },
        2: { info:'22222. Some random info here', lat:46.0553, lng:14.5144 },
        3: { info:'33333. Some random info here', lat:-33.7333, lng:151.0833 },
        4: { info:'44444. Some random info here', lat:27.9798, lng:-81.731 }
    };
    var map = new google.maps.Map(document.getElementById('map_2385853'), {
        zoom: 1,
        maxZoom: 8,
        minZoom: 1,
        streetViewControl: false,
        center: new google.maps.LatLng(40, 0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var infowindow = new google.maps.InfoWindow();

var auto_remove = true;//When true, markers for all unreported locs will be removed.

function setMarkers(locObj) {
    if(auto_remove) {
        //Remove markers for all unreported locs, and the corrsponding locations entry.
        $.each(locations, function(key) {
            if(!locObj[key]) {
                if(locations[key].marker) {
                    locations[key].marker.setMap(null);
                }
                delete locations[key];
            }
        });
    }

        $.each(locObj, function(key, loc) {
            if(!locations[key] && loc.lat!==undefined && loc.lng!==undefined) {
                //Marker has not yet been made (and there's enough data to create one).

                //Create marker
                loc.marker = new google.maps.Marker({
                    position: new google.maps.LatLng(loc.lat, loc.lng),
                    map: map
                });

                //Attach click listener to marker
                google.maps.event.addListener(loc.marker, 'click', (function(key) {
                    return function() {
                        infowindow.setContent(locations[key].info);
                        infowindow.open(map, locations[key].marker);
                    }
                })(key));

                //Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
                locations[key] = loc;
            }
            else if(locations[key] && loc.remove) {
                //Remove marker from map
                if(locations[key].marker) {
                    locations[key].marker.setMap(null);
                }
                //Remove element from `locations`
                delete locations[key];
            }
            else if(locations[key]) {
                //Update the previous data object with the latest data.
                $.extend(locations[key], loc);
                if(loc.lat!==undefined && loc.lng!==undefined) {
                    //Update marker position (maybe not necessary but doesn't hurt).
                    locations[key].marker.setPosition(
                        new google.maps.LatLng(loc.lat, loc.lng)
                    );
                }
                //locations[key].info looks after itself.
            }
        });
    }

    var ajaxObj = {//Object to save cluttering the namespace.
        options: {
            url: "........",//The resource that delivers loc data.
            dataType: "json"//The type of data tp be returned by the server.
        },
        delay: 10000,//(milliseconds) the interval between successive gets.
        errorCount: 0,//running total of ajax errors.
        errorThreshold: 5,//the number of ajax errors beyond which the get cycle should cease.
        ticker: null,//setTimeout reference - allows the get cycle to be cancelled with clearTimeout(ajaxObj.ticker);
        get: function() { //a function which initiates 
            if(ajaxObj.errorCount < ajaxObj.errorThreshold) {
                ajaxObj.ticker = setTimeout(getMarkerData, ajaxObj.delay);
            }
        },
        fail: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
            ajaxObj.errorCount++;
        }
    };

    //Ajax master routine
    function getMarkerData() {
        $.ajax(ajaxObj.options)
          .done(setMarkers) //fires when ajax returns successfully
          .fail(ajaxObj.fail) //fires when an ajax error occurs
          .always(ajaxObj.get); //fires after ajax success or ajax error
    }

    setMarkers(locs);//Create markers from the initial dataset served with the document.
    //ajaxObj.get();//Start the get cycle.

    // *******************
    //test: simulated ajax
    /*
    var testLocs = {
        1: { info:'1. New Random info and new position', lat:-37, lng:124.9634 },//update info and position and 
        2: { lat:70, lng:14.5144 },//update position
        3: { info:'3. New Random info' },//update info
        4: { remove: true },//remove marker
        5: { info:'55555. Added', lat:-37, lng:0 }//add new marker
    };
    setTimeout(function() {
        setMarkers(testLocs);
    }, ajaxObj.delay);
    */
    // *******************
});

目前的code的底部,你会发现一个 testLocs 数据集,展示了可能性的范围初始数据集后添加/删除/更新标记得到了应用。

At the bottom of the code, you'll find a testLocs dataset, demonstrating the range of possibilities for adding/removing/updating markers after the initial dataset has been applied.

我没有测试过的阿贾克斯完全,但它模拟与 testLocs 数据集。

I've not tested the ajax fully, but have simulated it with the testLocs dataset.

请参阅 演示

See DEMO

10秒后, testLocs 将被应用,你会看到各种变化的标志(在信息窗口中显示的信息)。请特别注意,更新的数据并不需要是完整的 - 只是指明了修改

After 10 seconds, testLocs will be applied and you will see various changes to the markers (and the info displayed in the infowindow). Note in particular that update data doesn't need to be complete - just specify the changes.

您将需要安排你的服务器:

You will need to arrange for your server to :

  • 构建初始数据集,下面我 LOCS 的例子。
  • 返回JSON-CN codeD集,下面我 testLocs 例的一般格式。
  • build the initial dataset, following my locs example.
  • return JSON-encoded datasets, following the general format of my testLocs example.

我已经包括了所有的客户端$ C $必要获取新数据集℃。所有你需要做的是:

I have included all the client-side code necessary for fetching new datasets. All you need to do is :

  • 创建一个服务器端脚本(如get_markers.php),它返回正确的格式的JSON-CN codeD的数据集(如已经exaplined)。
  • 编辑该行 URL:........,指向服务器端脚本,如网​​址: get_markers.php
  • ;
  • 通过取消注释行 ajaxObj.get()激活循环AJAX程序
  • 确保模拟AJAXcode块注释或删除掉。
  • create a server-side script (eg. "get_markers.php") which returns a json-encoded dataset of the right format (as already exaplined).
  • edit the line url: "........", to point to the server-side script, eg url: "get_markers.php".
  • activate the cyclic ajax process by uncommenting the line ajaxObj.get();.
  • ensure the "simulated ajax" code block is commented out or removed.

我添加了一个布尔行为开关名为 auto_remove 。如果设置为真,code一小笔额外块将运行,从而导致被删除所有标记为未报告的初始位置。

I have added a boolean "behavioural switch" named auto_remove. When set to true, a small additional block of code will run, causing all markers for unreported locs to be removed.

这将允许您报告所有的有效的标记在每次迭代。清除会自动发生,无需主动指挥他们。

This will allow you to report all active markers at every iteration. Removals will happen automatically, without needing to actively command them.

在code这是为了响应 {删除:真} 还是很到位的,所以(与 auto_remove 设置为)清除即可EX pressly吩咐,如果你需要的话。

The code which responds to { remove: true } is still in place, so (with auto_remove set to false) removals can be expressly commanded if you ever need to do so.

更新 演示

Updated DEMO

PHP脚本应建立以下形式的数组:

The PHP script should build an array of the following form :

<%php
$testLocs = array(
    'loc1' => array( 'info' => '1. New Random info and new position', 'lat' => 0, 'lng' => 144.9634 ),
    'loc2' => array( 'lat'  => 0, 'lng' => 14.5144 ),
    'loc3' => array( 'info' => '3. New Random info' ),
    'loc5' => array( 'info' => '55555. Added', 'lat' => 0, 'lng' => 60 )
);
echo json_encode($testLocs);
exit();
%>

我不知道PHP是否会处理数字键。如果没有,那么试试字符串, 1 '2'等,这可能是最安全的,让所有密钥的字母preFIX,例如。 LOC1LOC2等,无论你选择做什么,确保在JavaScript中的键 LOCS 对象是同一类型和组成。

I'm not sure whether PHP will handle numeric keys. If not, then try strings, '1', '2' etc. It's probably safest to give all keys an alphabetic prefix, eg. 'loc1', 'loc2' etc. Whatever you choose to do, make sure the keys in the javascript locs object are of the same type and composition.

这篇关于只有谷歌地图V3自动刷新标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆