2011-09-15 89 views
0

是否可以通過onclick激活地理位置js?我可以激活Google Maps API地理位置嗎?

如果我在地圖中包含地理位置代碼(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); 
    } 

}); 

回答

2

是的,這是可能的。嘗試包括你的$(document)的點擊事件代碼。就緒(函數()塊,像這樣:

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

我只是做了一些測試,與您的代碼,一旦我在$包含它,它爲我工作(document).ready handler。

+0

謝謝你,我一直在尋找一種方法,從onload移動到onclick按鈕,這個工作很好。 –

相關問題