Access the Flickr API to retrieve the image ID and then use it in a subsequent request

Utilizing Angular JS, my objective involves retrieving a list of Flickr images based on location. The image IDs obtained from the initial request need to be passed into another request to gather additional information for each photo displayed in the results. Despite my efforts, I am encountering difficulties with obtaining the correct value from the second search function. While the question may seem lengthy, all I really need help with is acquiring the accurate value within my second function so that it can be assigned to the results.

The code snippet below resides in my services.js file:

//flickr location search
APIRequest.fkrSearch = function(lat, lon, rad){
    fkrAPI = $resource('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=5956ffe850b325e0b121525800af5b31&lat='+lat+'&lon='+lon+'&radius=5km&format=json&nojsoncallback=1', { dataType: 'jsonp', jsonp: 'jsoncallback' });
    return fkrAPI.get().$promise.then(function (data){
        console.log(data);
        return data;
        });
    }; 

Here is the corresponding request within my controller:

$scope.resultPosts = []; //global variable to hold results

if ($scope.locationSearch.dataSource.fkr){
                $scope.fkrLoading = true;
                console.log('search Flickr');
                OSINTAPIRequest.fkrSearch($scope.lat, $scope.lng, $scope.radius).then(function(data){
                    if (data.error){
                            toastr.error(data.error.error_msg, 'Flickr Error['+data.error.error_code+']');
                        } else {
                            if (data.photos.photo.length > 0){
                                var fkrAppend = 0;
                                for(var i=0; i < data.photos.photo.length; i++){
                                    fkrAppend++;

                                    var fkrImageId = data.photos.photo[i].id;

                                    $scope.resultPosts.push({
                                                        SourcePostID: data.photos.photo[i].id,
                                                        Timestamp: '',
                                                        PostLatitude: $scope.fkrGetLatLng(data.photos.photo[i].id),
                                                        PostLongitude: $scope.fkrGetLatLng(data.photos.photo[i].id),
                                                        PostMedia: 'https://farm'+data.photos.photo[i].farm+'.staticflickr.com/'+data.photos.photo[i].server+'/'+data.photos.photo[i].id+'_'+data.photos.photo[i].secret+'.jpg',
                                                        PostType: 'image',
                                                        PostAvatar: 'https://pingendo.github.io/pingendo-bootstrap/assets/user_placeholder.png',
                                                        PostMarker: 'assets/img/fkrMarker.png',
                                                        DataSource: 'flickr',
                                                        Display:$scope.resultFilter.fkr

                                        });

                                } 

In this scenario, the fkrGetLatLng function returns a list of image IDs for geotagged photos at the specified latitude and longitude but fails to provide actual location data in the results necessary for plotting points on the map. The line

(PostLatitude: $scope.fkrGetLatLng(data.photos.photo[i].id))
attempts to pass the returned image ID to the fkrGetLatLng function, which is structured as follows:

$scope.fkrGetLatLng = function (fkrImageId){
        OSINTAPIRequest.fkrGetLatLong(fkrImageId).then(function(data){
            var fkrLat = data.photo.location.latitude;
            var fkrLng = data.photo.location.longitude;
            //console.log (fkrLat+','+fkrLng);
            return fkrLat;

    });
}

The following section covers the request contained within the services JS, where both requests yield correct data but encounter issues assigning the PostLatitude field the appropriate value:

//flickr location search - get lat long
APIRequest.fkrGetLatLong = function(fkrImageId){
        fkrAPI = $resource('https://api.flickr.com/services/rest/?method=flickr.photos.geo.getLocation&api_key=5956ffe850b325e0b121525800af5b31&photo_id='+fkrImageId+'&format=json&nojsoncallback=1', { dataType: 'jsonp', jsonp: 'jsoncallback' });
        return fkrAPI.get().$promise.then(function (data){
            //console.log(data);
            return data;
        });
    };

Answer №1

It seems like the function you are using to assign the latitude and longitude values is asynchronous, which means you might be assigning them before they are resolved. To solve this issue, consider fetching the data first and then assigning it afterwards. You can follow a similar approach as shown below:

  var photoId = data.photos.photo[i].id;
  $scope.fetchLatLng(data.photos.photo[i].id).
  then(function(data){
      $scope.resultPosts.push({
                SourcePostID: data.photos.photo[i].id,
                Timestamp: '',
                PostLatitude: data.lat,
                PostLongitude: data.long,
                PostMedia: 'https://farm'+data.photos.photo[i].farm+'.staticflickr.com/'+data.photos.photo[i].server+'/'+data.photos.photo[i].id+'_'+data.photos.photo[i].secret+'.jpg',
                PostType: 'image',
                PostAvatar: 'https://pingendo.github.io/pingendo-bootstrap/assets/user_placeholder.png',
                PostMarker: 'assets/img/fkrMarker.png',
                DataSource: 'flickr',
                Display:$scope.resultFilter.fkr

      });

 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: undefined property causing inability to convert to lowercase

I am encountering an error that seems to be stemming from the jQuery framework. When I attempt to load a select list on document ready, I keep getting this error without being able to identify the root cause. Interestingly, it works perfectly fine for the ...

Discovering the Newest Product Updates through API Integration

I have a component that displays only the most recent product fetched from an API: const about = ({products}) => { const data = products.attributes console.log(data) return ( <div> <h1>{data.Name}</h1> ...

The Laravel Ajax Request is Returning Null

I am faced with a perplexing issue involving a toggle button that should change the status (Show/Hide). Despite sending valid data via ajax and seeing correct data in the console, the request appears empty in the controller. I've made sure to include ...

The authorization process for uploading data to Azure Data Lake Gen2

Currently, I am working on generating a Shared Access Signature (SAS) client-side within my Node.js application. The primary goal is to allow users to directly upload files to my Azure Data Lake Gen2 Blob Storage container without streaming them through th ...

Tips for passing several parameters through an AJAX POST call in Yii2 framework

My view consists of a detailview and a gridview. The grid view has check-boxes for all the columns, while the detail view contains the model id. What I need is to select a column from the grid view, and upon clicking on an a link button, send an ajax call ...

Javascript Dependencies Are Failing to Load with Ajax

My index.php file has the functionality to load content based on a $_GET variable. Here's how it works... <?php $problem_id = $_GET['problem_id']; include('include/' . $problem_id . '.php'); ?> For example, ...

AngularJS route not being resolved upon initial page rendering

Looking to integrate an AngularJS router into my application, I've defined a route in angular.module('MyModule').config(): $routeProvider .when('/:stepId?', { templateUrl: EditorApp.webDir + 'bundles/innovapath/a ...

Grab the current URL using useRouter in a Next.js app

I am using userouter to obtain the URL of the current page and then utilizing the clipboard to copy it. However, I am encountering an issue where the copied content shows as object object instead of the expected URL. Can someone please help me identify w ...

Limit the input to numbers when pasting into Angular

Implementing a directive in <input type='text'> to restrict user input to numbers has been successful! The issue arises when a user copies and pastes a string, causing Angular to accept the value and send it to the backend. angular.module ...

EmberJS - how to register a precompiled handlebars template

In my EmberJS application, I have precompiled all of my handlebars templates so that they are loaded as pure Javascript files. However, I am encountering an issue where these precompiled templates are not being added to the Ember container as expected. In ...

I am looking to implement custom styles to a navigation bar element upon clicking it

When I attempted to use useState(false), it ended up applying the styles to all the other elements in the navbar. import React, { useState } from 'react'; import { AiOutlineMenu } from 'react-icons/ai'; import { Navbar, NavContainer, Na ...

Printing an array of objects using Java

Despite the numerous resources available on this topic, I'm finding it difficult to comprehend in my specific scenario. The task at hand is to print an array of objects. For instance, I have an array containing objects from the "shape" class. Should ...

Changing the URL locale using Next.js router.push is unsuccessful

I am attempting to switch the locale by connecting the onClick event to two separate <div> elements: import { useRouter } from 'next/router' // other codes const router = useRouter() const changeLocale = (locale) => { router.push({ ...

Assistance with selecting elements using jQuery

I'm facing a challenge with a code that I cannot change. My goal is to introduce a selector that can choose (upon clicking) all elements below it until the next occurrence of the main element. The catch is that they are not nested, just stacked on top ...

Bringing out the version information in a React/webpack application: A guide

Looking for a way to display the version of every build in your app? I attempted to follow a tutorial to achieve this, but unfortunately, it didn't work for me. The tutorial I used can be found here: Do you know of any other methods that could help a ...

Removing/modifying selected choices in an element

I have implemented a material ui select element with the ability to make multiple selections using checkboxes. My query is, can I incorporate the functionality to delete or update names directly from the select element itself? For instance, by clicking on ...

How can I dynamically change the default value of the selected option dropdown in React-Select when a new option is chosen?

Can you help me understand how to update the default displayed value on a dropdown in a react-select component? When I choose a different option from one dropdown, the select dropdown value does not change. I've attempted this.defaultValue = option.va ...

Exploring the World of AngularJS Modules

I'm a beginner in AngularJS and currently learning the ropes. I came across this syntax: var app = angular.module('myApp', ['ngRoute']); My question is, what does it mean when square brackets are used [ ]? What roles or function ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

Initiate movement upon scrolling

I would like to activate this box animation once the user scrolls down by adding a class. I'm having trouble getting this to work, it seems like I might be missing something crucial. Here is my current code, can someone point out where I am going wro ...