我可以激活Google Maps API Geolocation onclick吗?

时间:2011-09-15 13:25:50

标签: javascript google-maps

是否可以通过onclick激活地理位置js?

如果我将地理位置代码(http://code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation)包含在我的地图中,它可以正常工作,但会启动代码onload。

我想要做的是让用户选择使用按钮进行地理定位。我已经尝试将相关代码移动到onclick()函数中,但这似乎没有诀窍。

这是我的代码:

function initialize() {
var latlng = new google.maps.LatLng(51.5146984674518, -0.0723123550415039);
var myOptions = {
  zoom: 14,
  center: latlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControl: true,
    mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
    position: google.maps.ControlPosition.RIGHT_BOTTOM
},
panControl: true,
    panControlOptions: {
    position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
    style: google.maps.ZoomControlStyle.LARGE,
    position: google.maps.ControlPosition.TOP_RIGHT
},
streetViewControl: false,
};
var map = new google.maps.Map(document.getElementById("energymap"),
    myOptions);
}

$('a#geolocate').click(function() {
// Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  // Try Google Gears Geolocation
  } else if (google.gears) {
    browserSupportFlag = true;
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeoLocation(browserSupportFlag);
    });
  // Browser doesn't support Geolocation
  } else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }

  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("Geolocation service failed.");
      initialLocation = newyork;
    } else {
      alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
      initialLocation = siberia;
    }
    map.setCenter(initialLocation);
  }

}); 

1 个答案:

答案 0 :(得分:2)

是的,有可能。尝试在$(document).ready(function()块中包含click事件代码,如下所示:

$(document).ready(function() {
  $('a#geolocate').click(function() { 
       ....
  });
});

我刚刚用你的代码做了一些测试,一旦我将它包含在$(document).ready处理程序中,它就适用于我。