Reputation: 68
Is it possible to synchronize users location using geolocation?, so that if the user is travelling his location will be updated on the page, some what like navigating his location...
i have tried this but, whole map keeps refreshing and takes time to load... It works fine, but, is there a better way that I can keep a track of users location?
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="../dist/geolocationmarker-compiled.js"></script>
<script>
var map, GeoMarker;
setInterval (function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
console.log('updating');
GeoMarker.setMap(map);
},10000);
google.maps.event.addDomListener(window, 'load', initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
</script>
<body>
<div id="map_canvas"></div>
</body>
Upvotes: 3
Views: 241
Reputation: 161384
Don't recreate the map when the position changes, just update the marker's position on the map.
var map, GeoMarker;
function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
}
setInterval (function() {
if (!GeoMarker) {
GeoMarker = new GeolocationMarker();
}
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
console.log('updating');
GeoMarker.setMap(map);
},10000);
google.maps.event.addDomListener(window,'load',initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
Upvotes: 1