Reputation: 65
I am using two brilliant packages named dburles:google-maps
and mdg:geolocation
. What I nee is to add a marker and change map's zoom automatically when I get user's geolocation data (after he allows it to share).
Template.onCreated
I have the following code:Template.dealersMap.onCreated(function() {
Tracker.autorun(() => {
this.latLng = new ReactiveVar(Geolocation.latLng());
})
});
onRendered
I do the following:Template.dealersMap.onRendered(function() {
navigator.geolocation.getCurrentPosition((position) => {
GoogleMaps.ready('exampleMap', (map) => {
let marker;
if(!this.latLng.get())
console.log('Didn\'t get the location..');
if(!marker) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(
this.latLng.get().lat,
this.latLng.get().lng
),
map: map.instance
});
} else {
marker.setPosition(this.latLng.get());
}
map.instance.setCenter(marker.getPosition());
map.instance.setZoom(11);
}, () => {
console.log('deny');
});
})
});
As result after user allows me to get his geodata nothing happens. But if user changes at least one step map zoom — everything works.
The question is — how to make this code work without letting user change map zoom?
Upvotes: 0
Views: 36
Reputation: 65
I just removed navigator.geolocation.getCurrentPosition
and now everything works fine. Here is the successful code:
Template.dealersMap.onCreated(function() {
this.latLng = new ReactiveVar();
Tracker.autorun(() => {
this.latLng.set(Geolocation.latLng());
})
});
Template.dealersMap.onRendered(function() {
this.autorun(() => {
GoogleMaps.ready('exampleMap', (map) => {
console.log('map is ready');
let marker;
if(!this.latLng.get()) {
console.log('Didn\'t get the location..');
} else {
if(!marker) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(
this.latLng.get()
.lat,
this.latLng.get()
.lng
),
map: map.instance
});
} else {
marker.setPosition(this.latLng.get());
}
}
map.instance.setCenter(marker.getPosition());
map.instance.setZoom(11);
})
})
});
Upvotes: 1
Reputation: 1128
You can use Tracker
to rerun the once the dta is changed like, once uses share his/her location, the marker is triggered. Here is the example code:
Template.dealersMap.onRendered(function() {
var self=this;
navigator.geolocation.getCurrentPosition((position) => {
GoogleMaps.ready('exampleMap', (map) => {
self.autorun(function() { //tracker function
let marker;
if(!this.latLng.get())
console.log('Didn\'t get the location..');
if(!marker) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(
this.latLng.get().lat,
this.latLng.get().lng
),
map: map.instance
});
} else {
marker.setPosition(this.latLng.get());
}
map.instance.setCenter(marker.getPosition());
map.instance.setZoom(11);
}, () => {
console.log('deny');
}
});
})
});
Upvotes: 0