Blog

How to save a geopoint with API

by on February 8, 2015

In other posts, we have described how to set up a sample Geolocation data set and how to retrieve geopoints using the API. The geopoints in your application would not be the ones from the sample data set, we used it only to make it easier to get started with Backendless Geolocation. Adding geopoints to your Backendless backend can be done either with the API or by using data import. In this post, we will review the first approach – saving geopoints with API.

From our introduction to geolocation, you might know that a geopoint consists of the following:

  • A pair of GPS coordinates: latitude and longitude,
  • A category the geopoint belongs to,
  • Optional metadata which is a collection of arbitrary name/value pairs.

The sample code below saves two geopoints in your Backendless backend. One point which represents Dallas, TX on the map is added using the synchronous API. The other one represents Houston, TX and is added with the asynchronous API call. Notice that both geopoints are added to the “cities” category, which will be created dynamically on the server if it does not exist. There is also some metadata such as the city name, population size and a URL of an image of the city skyline:

       AsyncCallback addPointCallback = new AsyncCallback<GeoPoint>() {
           @Override
           public void handleResponse(GeoPoint savedGeoPoint) {
               Log.i(TAG, "ASYNC: geo point saved. Object ID - " + savedGeoPoint.getObjectId());
           }
    
           @Override
           public void handleFault(BackendlessFault fault) {
               Log.e(TAG, fault.getMessage());
           }
       };
    
       GeoPoint houstonTX = new GeoPoint(29.76429, -95.38370);
       houstonTX.addCategory("cities");
       houstonTX.addMetadata("city", "Houston");
       houstonTX.addMetadata("population", 2196000);
       houstonTX.addMetadata("photo", "http://en.wikipedia.org/wiki/Houston#mediaviewer/File:Uptown_Houston.jpg");
    
       Backendless.Geo.savePoint(houstonTX, addPointCallback);

       val addPointCallback = object : AsyncCallback<GeoPoint> {
           override fun handleResponse(savedGeoPoint: GeoPoint) {
               Log.i(TAG, "ASYNC: geo point saved. Object ID - ${savedGeoPoint.objectId}")
           }
    
           override fun handleFault(fault: BackendlessFault) {
               Log.e(TAG, fault.message)
           }
       }
    
       val houstonTX = GeoPoint(29.76429, -95.38370)
       houstonTX.addCategory("cities")
       houstonTX.addMetadata("city", "Houston")
       houstonTX.addMetadata("population", 2196000)
       houstonTX.addMetadata("photo", "http://en.wikipedia.org/wiki/Houston#mediaviewer/File:Uptown_Houston.jpg")
    
       Backendless.Geo.savePoint(houstonTX, addPointCallback)

    NSDictionary *metadata = @{@"city": @"Dallas", @"population": @1258000, @"photo": @"http://en.wikipedia.org/wiki/Dallas#mediaviewer/File:Xvixionx_29_April_2006_Dallas_Skyline.jpg"};
    GeoPoint *dallasTX = [[GeoPoint alloc] initWithLatitude:32.803468 longitude:-96.769879 categories:@[@"cities"] metadata:metadata];
    [Backendless.shared.geo saveGeoPointWithGeoPoint:dallasTX responseHandler:^(GeoPoint *savedGeoPoint) {
        NSLog(@"Geo point saved. Object ID - %@", savedGeoPoint.objectId);
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];

    let metadata = ["city": "Dallas", "population": 1258000, "photo": "http://en.wikipedia.org/wiki/Dallas#mediaviewer/File:Xvixionx_29_April_2006_Dallas_Skyline.jpg"] as [String : Any]
    let dallasTX = GeoPoint(latitude: 32.803468, longitude: -96.769879, categories: ["cities"], metadata: metadata)
    Backendless.shared.geo.saveGeoPoint(geoPoint: dallasTX, responseHandler: { savedGeoPoint in
        print("Geo point saved. Object ID - \(savedGeoPoint.objectId ?? "")")
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const saveGeoPoint = () => {
      const houstonTX = new Backendless.GeoPoint()
    
      houstonTX.latitude = 29.76429
      houstonTX.longitude = -95.38370
      houstonTX.categories = ['cities']
      houstonTX.metadata = {
        city      : 'Houston',
        population: 2196000,
        photo     : 'https://upload.wikimedia.org/wikipedia/en/thumb/7/76/Houston_Collage.png/800px-Houston_Collage.png'
      }
    
      return Backendless.Geo.savePoint(houstonTX)
    }
    
    const onSuccess = point => {
      console.log(`geo point saved. Object ID - ${ point.objectId }`)
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    Promise.resolve()
      .then(saveGeoPoint)
      .then(onSuccess)
      .catch(onError)
    

    GeoPoint houstonTX = GeoPoint.fromLatLng(29.76429, -95.38370);
    houstonTX
     ..categories = ["cities"]
     ..metadata = {
       "city": "Houston",
       "population": 2196000,
       "photo": "http://en.wikipedia.org/wiki/Houston#mediaviewer/File:Uptown_Houston.jpg"};
    
    Backendless.Geo.savePoint(houstonTX).then(
     (savedGeoPoint) => print("ASYNC: geo point saved. Object ID - ${savedGeoPoint.objectId}"));

    After you run the code above, you can verify that the geopoints are added to the backend using Backendless Console:

    1. Login to Backendless Console, select the app and click the Geolocation icon.
    2. Click the cities category; the Console should show the points as in the screenshot below:

    Enjoy!