在bing地图上移动gelocation

时间:2015-08-28 07:53:25

标签: javascript geolocation bing-maps

需要将动态位置图钉移动到我从html5 gelocation获得的位置。我尝试了一些其他的东西,但然后pushpin不断产生重复。移除图钉剂也可以。

var map = null;
var p = 0;
var x = document.getElementById("notice");
$(document).ready(function(){
  getLocation();
  watchPosition();
});
function watchPosition() {
  //map options
  var mapOptions = {
    credentials: "key here",
    mapTypeId: Microsoft.Maps.MapTypeId.road,
    zoom: 19
  };
  //map initialization
  map = new Microsoft.Maps.Map(document.getElementById('mapDiv'), mapOptions);
}
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(success, error, {maximumAge: 5000,
                                                         enableHighAccuracy: true});
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function error(err) {
  x.innerHTML = err.toString();
}
function success(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
  var pos = new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude);
  //console.log(pos);
  p++;
  console.log(p);
  //infobox
  var offsetInfo = new Microsoft.Maps.Point(0, 30); 
  var infoboxOptions  = { title: "Location Information", description:   "This is your current location.", offset: offsetInfo };
  var callout = new Microsoft.Maps.Infobox(pos, infoboxOptions);
  //pushpin
  var offsetPin = new Microsoft.Maps.Point(0, 5);
  var pushpinOptions = {text : '1', visible: true, textOffset: offsetPin};
  var pushpin = new Microsoft.Maps.Pushpin(pos, pushpinOptions);
  map.setView({center:pos});
  if (p <= 1) {
    map.entities.push(pushpin);
  } else {
    pushpin.setLocation(pos);
    console.log(toString(pushpin.getLocation()));
  }
}

1 个答案:

答案 0 :(得分:0)

您遇到的问题是您不断创建新的Pushpin实例并设置它的位置。在第一个图钉后,没有添加其他图钉。您需要做的是创建一个全局图钉变量,只有在变量为null时才创建它,如果不是,则设置它的位置。以下是您的成功函数的修改版本:

var pushpin;

function success(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    var pos = new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude);

    p++;
    console.log(p);

    if(pushpin){
        pushpin.setLocation(pos);
    }else{
        //infobox
        var offsetInfo = new Microsoft.Maps.Point(0, 30); 
        var infoboxOptions  = { title: "Location Information", description:   "This is your current location.", offset: offsetInfo };
        var callout = new Microsoft.Maps.Infobox(pos, infoboxOptions);

        //pushpin
        var offsetPin = new Microsoft.Maps.Point(0, 5);
        var pushpinOptions = {text : '1', visible: true, textOffset: offsetPin};
        pushpin = new Microsoft.Maps.Pushpin(pos, pushpinOptions);
        map.entities.push(pushpin);
    }

    map.setView({center:pos});
}