Service in Angular JS dispatching coordinates to controller

I am in need of retrieving a path consisting of latitude and longitudes for displaying on a map within my app.

To handle all the API calls, I have set up a basic controller.

function mainController($scope, $http){

  $http.get('/api/lastrun')
    .success(function(data){
      $scope.lastrun = data;
    })
    .error(function(data){
      console.log('Error: ' + data);
    });
}

The 'lastrun' variable contains an array that provides access to each position along the path.

In addition, I have created a mapController using the angular-leaf-directive library.

function mapController($scope, positionService){
  angular.extend($scope, {
              run: {
                  lat:  0.0,
                  lng:  0.0,
                  zoom: 4
              },
              path: {
                  p1: {
                      color: 'red',
                      weight: 2,
                      latlngs: [
                          { lat: 51.50, lng: -0.082 }, //example of lat and lng here
                          { lat: 48.83, lng: 2.37 },
                          { lat: 0, lng: 7.723812 }
                      ]
                  }
                }
          });
}

It seems like a fairly straightforward task - simply adding the array of positions obtained from /api/lastrun into the 'latlngs' property of my mapController.

Although I do not have extensive experience with AngularJS Services, I attempted to create my own (positionService), which unfortunately did not yield the desired outcome.

If anyone has suggestions on how I can utilize my service to generate an array containing a series of {lat : , lng: } pairs and integrate it into my mapController, your assistance would be greatly appreciated.

Answer №1

In the situation, I would have taken the following approach:

$scope.lastrun = [];
$http.get('/api/lastrun')
    .success(function(data){
       angular.forEach(data, function (value) {
         $scope.lastrun.push({lat : value.lat, lng : value.lng});
       });
     }
    })

Subsequently:

path: {
              p1: {
                  color: 'blue',
                  weight: 3,
                  latlngs: $scope.lastrun
              }

I trust this solution will be beneficial.

Answer №2

I've come across a solution that works for me. I implemented Adrien's solution in my service rather than in my controller, and then passed the lastrunpos array back to my mapController. Here is the code snippet:

var selftracking = angular.module('selftracking',["leaflet-directive"])

  selftracking.service('positionService', function($http){
    var lastrunpos = [];
    $http.get('/api/lastrun')
      .success(function(data){
        angular.forEach(data.path, function (value) {
         lastrunpos.push({lat : value.latitude, lng : value.longitude});
       });
     });
     return {
       getPos : function() {
          return lastrunpos;
       }
     }
  });

function mainController($scope, $http){
  //Retrieve all latest activities for the front page
  $http.get('/api/lastactivity')
    .success(function(data){
      $scope.lastactivity = data;
    })
    .error(function(data){
      console.log('Error: '+ data);
    });
  $http.get('/api/lastrun')
    .success(function(data){
      $scope.lastrun = data;
    })
    .error(function(data){
      console.log('Error: ' + data);
    });
}

function mapController($scope, positionService){
  angular.extend($scope, {
              run: {
                  lat: 51.505,
                  lng: -0.09,
                  zoom: 4
              },
              path: {
                  p1: {
                      color: 'red',
                      weight: 8,
                      latlngs: positionService.getPos()
                  }
                }
          });
}

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

Fulfill all of the promises within Bluebird, as well as decline any that do

I am in search of a method to retrieve both successful resolutions and rejections from a promise array. I am relying on the Bluebird implementation, so any ES6 compatible solution would be preferable. One option that comes to mind is utilizing Bluebird&ap ...

Exploring the effectiveness of testing Svelte components

Looking to test a component that utilizes a third-party module without mocking the imported components? Check out this example: // test.spec.ts import Component from "Component"; describe('Component', () => { test('shoul ...

Enhancing middleware chaining in Express

Below is the code for my Express configuration: var server = express() .use(express.cookieParser()) .use(express.session({secret: buffer.toString('hex')})) .use(express.bodyParser()) .use(express.static('./../')); serv ...

Javascript enables dynamic field addition to tables

I have JSON data that needs to be displayed in an HTML table. To input the values, I have individual fields for firstname, lastname, email, and phone number, along with an "Add Row" button. When I click the "Add Row" button, I want the entered values to b ...

The power of the V8 JavaScript engine: Understanding v8::Arguments and the versatility of function

I have created a Node.js addon that wraps a C++ standard library element std::map<T1,T2>. The goal is to expose this map as a module with two primary functions: Set for adding new key-value pairs and Get for retrieving values by key. I want to create ...

ways to retrieve script template variable in angularjs application

I have written scripts to create a whiteboard using canvas inside the template page of AngularJS. Now I need to assign the values of the points[] variable to an AngularJS scope variable. <script> var points = []; </script> How can I access th ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

Finding the way to locate obsolete or deprecated packages in NPM versions

Is there a way to easily identify outdated deep dependencies in the local node_modules folder, separate from the top-level packages? After running the command: npm install with this content in my package.json: "dependencies": { "bluebi ...

How to Calculate Dates in Javascript

Currently exploring the realm of JavaScript, I find myself in the process of developing a dashboard for an e-commerce platform that I am currently involved with. My goal is to display data for all dates starting from the date of the initial order placed. M ...

"Is there a way to retrieve "Lorem ipsum" information from a web service in JSON format

Does anyone know of any sample web services that serve JSON data? I'm looking to practice consuming JSON for testing and learning purposes. I would even be interested in downloading JSON files with images and other content to study offline. Perhaps th ...

Angular Controller is not able to retrieve the Route Parameter, resulting in a 404

Currently working on my very first web app using Node.js and AngularJs. I've encountered a roadblock with the following code: var app = angular.module('Martin', ['ngResource','ngRoute']); app.config(['$routeProvide ...

Is it possible to retrieve the controller path for an AJAX request from within a partial view?

Looking for a solution to fully decouple and reuse a partial view that allows users to select dates and filter results based on those dates. This widget can be used on multiple pages, so I wanted to add event listeners that would submit the form within the ...

What is the solution to adding values from a counter?

I am trying to create a JavaScript counter: function animateSun() { var $elie = $("#sun"); $({ degree: 0 }).animate({ degree: 360 }, { duration: 190999, easing: 'linear', step: function(val) { now = Math.round ...

I am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...

The AJAX request fails to trigger following the onbeforeunload event except when the page is manually refreshed

I'm currently working on implementing a solution for handling the onbeforeunload event to display a custom message when the user tries to close the browser tab. I want a prompt like: Are you sure you want to leave this page? (I don't want to use ...

Using a JavaScript class rather than an ID for toggling visibility

As a complete newbie to JavaScript, I've come across similar questions but I'm lost when it comes to coding - help needed! So here's the code I have so far, and I'm hoping someone can assist me. Currently, I have JavaScript set up to s ...

Issue with Ionic 4 button not triggering event when created using Jquery

Utilizing Ionic 4 in my current project, I have integrated it with Jquery. On the HTML page, a button is created using the following code: <ion-button (click)="event1()">EVENT1 </ion-button> In the .ts file for the page, a function is impleme ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

What is the best way to obtain root access and utilize disk usage (du) within the main process of Electron?

In the process of developing a macOS application with the help of Electron, I encountered an issue. Attempting to execute the following command from the main process using ipcMain and NodeJS's exec: // Navigating to a directory and utilizing disk us ...

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...