Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Geolocation Refreshing to Current Location

Hello everyone! Thank you for taking your time to help me out on this. As usually is the case, I am new to Titanium and Javascripting in general and have been sitting on this problem for a bit.

I am trying to create a map that focus's the current user's location, but whenever the user moves to have the map "refresh" and recenter the user to their new location on the map. I understand that there is a ticket that has had this same problem :

http://developer.appcelerator.com/question/36591/refresh-map-view-as-user-location–gps–changes

but there was no code exchanged and it has still left me in the dark.

I can get a map to work by simply having it within the "Titanium.Geolocation.getCurrentPosition" event, but I am not sure where to go from there or if even having the "win.add(mapview)" within that event is a good idea.

Here is the following code.

var win = Titanium.UI.currentWindow;

//
// Begin Geo Location
//

Titanium.Geolocation.purpose = "Recieve User Location";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;

Titanium.Geolocation.distanceFilter = 10;

var my_location = Titanium.Geolocation.getCurrentPosition(function(e) {
        if (e.error) {
            Ti.API.log('error: ' + JSON.stringify(e.error) );
            return;
        }

var current_longitude = e.coords.longitude;
var current_latitude = e.coords.latitude;
var current_altitude = e.coords.altitude;
var current_heading = e.coords.heading;
var current_accuracy = e.coords.accuracy;
var current_speed = e.coords.speed;
var current_timestamp = e.coords.timestamp;
var current_altitudeAccuracy = e.coords.altitudeAccuracy;
//
// Mapview
//
var mapview = Titanium.Map.createView({
mapType: Titanium.Map.STANDARD_TYPE,
animate:true,
regionFit:true,
userLocation:true,
region: {latitude: current_latitude, longitude: current_longitude, latitudeDelta:.01, longitudeDelta:.01},
});

win.add(mapview);

});

The following code is my attempt at solving the problem, but I often get a parse error, which I attribute to calling the "current_latitude" and "current_longitude" and it being out of the scope. But I have no idea how to call those variables to the bottom to be a part of the "EventListener".

mapview.addEventListener('regionChanged',function() {
    region:{latitude:current_latitude, longitude:current_longitude}
});
— asked January 6th 2011 by Hector Leiva
  • geolocation
  • gps
  • map
  • mapview
  • refresh
0 Comments

5 Answers

  • I have solved my own question. Here is the code I ended up using.

    Titanium.Geolocation.purpose = "Recieve User Location";
    Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
    
    // Set Distance filter. This dictates how often an event fires based on the distance the device moves. This value is in meters.
    Titanium.Geolocation.distanceFilter = 10;
    //set the mapview with the current location
    var mapview = Titanium.Map.createView({
        mapType: Titanium.Map.STANDARD_TYPE,
        animate:true,
        region: {latitude:39.30109620906199, longitude:-76.60234451293945, latitudeDelta:0.1, longitudeDelta:0.1},
        regionFit:true,
        userLocation:true,
        visible: true,
    });
    
    function getLocation(){
    //Get the current position and set it to the mapview
    Titanium.Geolocation.getCurrentPosition(function(e){
            var region={
                latitude: e.coords.latitude,
                longitude: e.coords.longitude,
                animate:true,
                latitudeDelta:0.001,
                longitudeDelta:0.001
            };
            mapview.setLocation(region);
    });
    }
    
    win.add(mapview);
    
    Titanium.Geolocation.addEventListener('location',function(){
        getLocation();
    });
    

    I thought that downvoting my question was uncalled for since I've been looking for something near this code example for over a week. Hope it helps any other new developers in the future.

    — answered January 7th 2011 by Hector Leiva
    permalink
    7 Comments
    • Thanks Hector,
      I too am new to Appcelerator and this was quite helpful.

      — commented February 3rd 2011 by Jordan Shaw
    • Thank you Hector. I've noticed the .distanceFilter is not in the documentation for Ti.Geolocation. how did you discover this?

      — commented May 5th 2011 by Joe Irvine
    • I noticed that quite a few people were using it on this forum. A lot of googling and testing it out let me know what it does.

      — commented May 5th 2011 by Hector Leiva
    • thanks hector , i was facing same problem and got solution with your code.
      thank you very much

      — commented April 4th 2012 by rajiv kumar
    • Thank you very much!

      — commented August 10th 2012 by Enrique Serrano
    • this code does not work in my application. The user location does not seem to update when walking around, only when zooming in and out on the map…

      — commented August 22nd 2012 by Joris
    • I would then try to make the Titanium.Geolocation.addEventListener('location' portion have a function that references function(e) instead of an empty function like in the previous example.

      So that it is :

      Titanium.Geolocation.addEventListener('location',function(e){
          getLocation();
      });
      

      If that doesn't work, I'd make it so that the function that centers the mapview inside the addEventListener has the same var region properties as the one before and a mapview.setLocation

      Titanium.Geolocation.addEventListener('location',function(e){
              var region={
                  latitude: e.coords.latitude,
                  longitude: e.coords.longitude,
                  animate:true,
                  latitudeDelta:0.001,
                  longitudeDelta:0.001
              };
              mapview.setLocation(region);
      });
      

      But be warned, this code is 2 years old now and the Titanium platform has changed extensively! They recommend through their documents on how to get the user's geolocation is to create an outside script that then is called by Ti.include(); into your application. Then to reference the methods within that application.

      — commented August 22nd 2012 by Hector Leiva
  • I don't see any reason for down-voting of your question. So, I gave it an up-vote so you're back to zero.

    For other developers, make sure to check the Kitchen Sink for code examples. It doesn't always have everything, but it covers a lot of the basics.

    Finally, I'm not entirely positive, but your solution code might have some issues due to the fact that the geolocation functionality is asynchronous. Just because you call getCurrentPosition() doesn't mean you'll immediately get new coordinates. Your mapview.setLocation(region) call could end up with old values, or I suppose even null values.

    You might want to wrap that call in a try/catch block or something to make sure that you don't cause an error.

    — answered January 7th 2011 by Tim Poulsen
    permalink
    2 Comments
    • I will do the try…catch in a bit; but would it also make sense to have another function get called from the EventListener be: Titanium.Geolocation.location?

      I was under the impression that having "location" would create the updated values. Like;

      function currentLocation(){
          Titanioum.Geolocation.location(function(e){
              var currentRegion={
                  latitude: e.coords.latitude,
                  longitude: e.coords.longitude,
                  animate:true,
                  latitudeDelta:.005,
                  longitudeDelta:.005
              };
              mapview.setLocation(currentRegion);
          });
      }
      
      Titanium.Geolocation.addEventListener('location',function(){
          currentLocation();
      });
      

      It looks silly to have an event listener with "location" and then have "Ti.Geolocation.location". I will see if this works out. But I wonder if it would be alright to have "getCurrentPosition" as long as it isn't referenced back in the addEventListener to try and get new values.

      — commented January 7th 2011 by Hector Leiva
    • Tim,

      His code working/not working has nothing to do with the fact that getCurrentPosition is asynchronous. He has put his code (mapview.setLocation()) within the callback for the Ti.Geolocation.getCurrentPosition() function. That means his code will ONLY get executed when the asynchronous call has come back with a result.

      The problem with his code is that he doesn't do any checking for success/failure of the event (e.g., if(e.success)…) or the presence of any meaningful values in e.coords. "try/catch" wouldn't have helped at all in catching those types of issues.

      Hector definitely had the right approach, it just needed some more checking for valid results.

      — commented October 27th 2011 by Joshua Nicholson
  • Anyone have the final code as im too having problem with the async function. I would like to create a button that can reposition the map to user current location. Can anyone shed some light? Thanx

    — answered April 20th 2011 by Aizil Akmar Omar
    permalink
    0 Comments
  • Anyone have the final code as im too having problem with the async function. I would like to create a button that can reposition the map to user current location. Can anyone shed some light? Thanx

    — answered April 20th 2011 by Aizil Akmar Omar
    permalink
    0 Comments
  • Hi Hector, I was looking through and running into the same problem with my geo location. I was curious if you had any break throughs with it and maybe could share with me what you had done to achieve this. Thanks for your help! -paul

    — answered August 22nd 2012 by paul wamser
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.