5

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.

2 Answers 2

3

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&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

proof of concept fiddle

3
  • Thanks. I had tried both with and without "pos" as a second parameter. Neither allowed me to access the lat/long from "getCurrentPosition". Your code will work as the marker is assigned locally. I would like to assign it from outside of the "getCurrentPosition" block. Commented Dec 21, 2015 at 20:34
  • 1
    The geolocation service is asynchronous, you need to use the position inside the callback when/where it is available. You can make the marker global if you would like it to move rather than get a new instance when the position changes (or if you want to move an existing marker).
    – geocodezip
    Commented Dec 21, 2015 at 21:05
  • Thanks, that makes perfect sense. Will do. Commented Dec 21, 2015 at 21:13
1

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;
3
  • Thanks for the response. I'm seeing something weird here. I have the code laid out as per your example, the only difference being based on geocodezip's answer. The "getCurrentPosition" function block is only calling a single parameter, "position". Oddly enough, "pos" in the "getCurrentPosition" block stores the current location lat/long. "the_position" takes the values from the "pos" object initially instantiated. So, the marker ends up being based on "the_position" which has the placeholder lat/long values. Very strange. Commented Dec 21, 2015 at 20:36
  • Thanks. I had tried that (assuming that map.setCenter should be set to "the_position" and not "pos"). This does center the map at my current location. However, as with using the variable "pos" instantiated outside of the block, this code makes a nice marker at lat 0, lng 0. Commented Dec 21, 2015 at 20:54
  • Still in the same boat, btw. Can't get the lat/long data of the current location out of the "getCurrentPosition" block. Commented Dec 21, 2015 at 21:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.