I have this simple script on a web page, loading a small kml file, but when I add geolocation, it always centers the map on the current location.
And I want to load the map centered on the kml file. User location should only be displayed if he is in the area of the kml, or if he drags the map to the area where he is located.
Accessorily, is there a way to easily refresh the user location on the map with javascript (maps api 3), without re-centering the map ?
var map;
function initialize() {
var centre = new google.maps.LatLng(4,4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.server.com/kmlfile.kml',
preserveViewport: false
});
ctaLayer.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
// map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn't support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
So, here is my latest update, I added the disableAutoPan: true option to infoWindow, as indicated, and to refresh the user position I used watchPosition in place of getCurrentPosition, together with setPosition to move theinfoWindow position :
var map;
function initialize() {
var center_map = new google.maps.LatLng(45,-4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.server.com/kmlfile.kml', preserveViewport: false
});
var ctaLayer.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if(typeof infowindow == "undefined") {
infowindow = new google.maps.InfoWindow({
disableAutoPan: true,
map: map, position: pos,
content: 'Your position',
zIndex: 0 /* not needed */
});
}
else {
infowindow.setPosition(pos);
}
}, function() {
/*handleNoGeolocation(true);*/
/* had to delete this because errors centered the map on North Pole */
},
{ timeout: 10000, enableHighAccuracy: true }); /* high accuracy for tests */
}
};
google.maps.event.addDomListener(window, 'load', initialize);
Apparently it works although I suppose it's quite raw...
See Question&Answers more detail:
os