Reputation: 97
I am trying to get user current location and pass those latitude/longitude coordinates to a map. The map will be used as a website background image.
I was partially successful with this code:
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
xss =position.coords.latitude +
"," + position.coords.longitude;
}
var position = [32.5590985,35.8415147];
Now I want the value of xss
to be inside this variable:
var position = [32.5590985,35.8415147];
basically I was trying to get the values from the function but without success.
How should I go about getting a value from inside the function?
HTML
<div id="googlemaps"></div>
JS Code
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
xss =position.coords.latitude +
"," + position.coords.longitude;
}
var position = [32.5590985,35.8415147];
function initialize() {
var myOptions = {
zoom: 17,
streetViewControl: false,
scaleControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('googlemaps'),
myOptions);
latLng = new google.maps.LatLng(position[0], position[1]);
map.setCenter(latLng);
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Upvotes: 0
Views: 168
Reputation: 55678
Assuming navigator.geolocation.getCurrentPosition
is asynchronous, this looks like a classic "Get results from an asynchronous request" problem. Please see https://stackoverflow.com/a/14220323/380487 for a detailed answer.
Upvotes: 0
Reputation: 5497
How about you set the value of position
variable from inside the showPosition
function?
var position;
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(pos) {
position = [pos.coords.latitude, pos.coords.longitude];
}
Upvotes: 1