JavaScript Google Maps API How to Store Location lat/long to Global Variable

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.

Answers:

Answer

The getCurrentPosition method is defined as (from the documentation):

navigator.geolocation.getCurrentPosition(success[, error[, options]])

Parameters

success - A callback function that takes a Position object as its sole input parameter.

error - Optional - An optional callback function that takes a PositionError object as its sole input parameter.

options - Optional - An optional PositionOptions object.

The way you are using it causes a local pos variable to be created (with the value of null).

function(position, pos) {

Just create the function signature with a single argument:

function(position) {

code snippet:

function initMap() {
  var infoWindow = new google.maps.InfoWindow();
  var pos = {
    lat: 42.1,
    lng: -74.1
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 42,
      lng: -74
    },
    zoom: 6
  });

  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      pos.lat = position.coords.latitude;
      pos.lng = position.coords.longitude;

      map.setCenter(pos);
      var marker = new google.maps.Marker({
        position: pos,
        map: map,
        title: 'Release Source'
      });
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter(), map);
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter(), map);
  }

  function handleLocationError(input, infoWindow, center, map) {
    infoWindow.setContent("ERROR: " + input);
    infoWindow.setPosition(center);
    infoWindow.open(map);
  }
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div id="map"></div>

proof of concept fiddle

Answer

If I understand you right... this should work. I've added a global variable called the_position which gets assigned a new value on each getCurrentPosition call.

var the_position = { // ADDED THIS
    lat: 0,
    lng: 0
}; 

function initMap() {

   ... all your current code

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

                                                 the_position.lat = position.coords.latitude; // ADDED THIS
                                                 the_position.lng = position.coords.longitude; // ADDED THIS

                                                 map.setCenter(pos);
                                                 }, function() {
                                                    handleLocationError(true, infoWindow, map.getCenter());
                                                 });
    }
    ... all your current code

}

Then when you want to retrieve the latest lat/lng just use...

// The Lat/Lng
var lat = the_position.lat;
var lng = the_position.lng;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.