Can I activate Google Maps API Geolocation onclick?
Is it possible to activate the geolocation js with an onclick?
If I include the geolocation code (http://code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation) into my maps it works fine but it initiates the code onload.
What I want to do is give the user the option to geolocate with a button. I've tried moving the relevant code into an onclick() function but that doesn't seem to do the trick.
Here is my code:
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(browserSuppor开发者_StackOverflow中文版tFlag);
});
// 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);
}
});
Yes, it is possible. Try including the click event code in your $(document).ready(function() block, like so:
$(document).ready(function() {
$('a#geolocate').click(function() {
....
});
});
I just did some tests with your code and it worked for me once I included it in the $(document).ready handler.
精彩评论