Reputation: 632
I want to use a function to get location using GPS and than use the coordinates(longitude and latitude) to modify the center of the map .
Here is a part of my code:
var lat;
var longi;
function initialize() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError, {
maximumAge: 3000,
enableHighAccuracy: true
});
function onGeoSuccess(event) {
lat = event.coords.latitude;
longi = event.coords.longitude;
alert(lat + ', ' + longi);
}
function onGeoError(event) {
lat = 50;
longi = 150;
}
} else {
lat = 50;
longi = 150;
};
var array;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(lat, longi),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
}
The problem is:The Alert is fine ,it displays the actual longitude and latitude but the map doesn't appear it gives just a small question mark.
Any help is aprreciated.
Upvotes: 0
Views: 1065
Reputation: 1282
Instead of using map.setCenter(lat,longi);
try:
map.set('center', new google.maps.LatLng(lat, longi));
Upvotes: 3
Reputation: 27765
You need to center map in onGeoSuccess
method:
Firs of all move map
variable higher:
var lat, longi, map;
Then on onGeoSuccess
method add setCenter
method call:
function onGeoSuccess(event){
lat=event.coords.latitude;
longi=event.coords.longitude;
map.setCenter( new google.maps.LatLng(lat, longi) );
}
And do that wherever you change lat, longi
values, in onGeoError
method too.
Also is better to use some default values for lat, longi
:
var lat = 50,
longi = 150,
map;
And move map initialization upper (don't forget to remove var
statement before map = new google.maps.Map
line):
function initialize() {
var array;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(lat, longi),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
// rest of your code
Upvotes: 2