I'm new to JavaScript, and am looking to implement the code provided by Google for putting a marker at your location. However, I'd like to take the location data and use it outside of the "getCurrentPosition" block.
My first pass was to instantiate an Object with lat and long as properties outside of the block and have this as a parameter of the function inside getCurrentPosition:
function initMap() {
var pos = {
lat: 42.1,
lng: -74.1
};
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 42, lng: -74},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position, pos) {
pos.lat = position.coords.latitude;
pos.lng = position.coords.longitude;
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Release Source'
});
}
The effect of this is that the marker will be at the position specified when the object is instantiated. These are placeholder values, as my current location is several states away.
'pos.lat = position.coords.latitude' and 'pos.lng = position.coords.longitude' are not overwriting the property values as set when the global "pos" object was instantiated.
The map is not centered on my current position, but based on the placeholder lat and long values originally assigned to "pos" when instantiated.
When I change to "navigator.geolocation.getCurrentPosition(function(position) { ... }",
this removes reference to the global "pos" variable inside of the "getCurrentPosition" block. It appears a local variable named "pos" is created.
The local instance of "pos" inside of the block will have its lat and long assigned based on my current location. The map is then centered around my current location, as per instruction in the block.
The marker will, however, be shown at the original lat long that were assigned as placeholder values when the global variable "pos" was instantiated.
Please let me know how I can get the current lat/long values data outside of the "getCurrentPosition" block and into the global "pos" object.