Inquire about RESTful service

Currently, I am just starting out with javascript and the angular.js framework. My main issue right now is that I'm having trouble getting ngResource to function properly.

Check out my code on Plunker

Here's a snippet of my code:

Javascript:

var geolocationControllers = angular.module('geolocationControllers', ['ngResource']);

geolocationControllers.controller('geolocationControllers', ['$scope', '$resource',
  function($scope, $resource) {

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        $scope.$apply(function() {
          $scope.position = $resource('http://nominatim.openstreetmap.org/reverse?format=json', {}, {
            query: {
              method: 'GET',
              params: {
                lat: position.coords.latitude,
                lon: position.coords.longitude
              }
            }
          });
          console.log($scope.position);
        });
      });
    }
  }
]);

HTML:

<div class="container" ng-controller="geolocationControllers">
    <label for="location">Your location:</label>
    <input type="text" id="location" size="120" ng-model="position"/>
</div>

This content will be displayed in the console and also within an input element:

function Resource(value) {          shallowClearAndCopy(value || {}, this);        }

Answer №1

If you want to achieve a similar result, you can follow these steps... I have personally tested this method in my own browser and it works perfectly; just make sure to customize the specific parts as needed.

HTML Markup

<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>untitled</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>

<body ng-controller="myController">

    <label for="location">Your location:</label><br>
    <input type="text" id="location" size="120" ng-model="positionText"/>

</body>
</html>

Javascript Functionality

var myApp = angular.module('myApp', []);

myApp.controller('myController', function ($scope, $http) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (curPosition) {
            var curLongi = curPosition.coords.longitude;
            var curLati = curPosition.coords.latitude;

            $http.get('http://nominatim.openstreetmap.org/reverse?format=json&lat='+curLati.toString()+'&lon='+curLongi.toString()).success(function (data) {
                    alert(JSON.stringify(data));
                    $scope.positionText = data.display_name;
            });


        });
    } 
});

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

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...

The command is not currently carrying out its function

I am attempting to verify whether the "sender" has either of the two specified roles, but for some reason the command is not being executed. There are no errors showing up in the console, it's just that the command doesn't run. const revAmount = ...

Transferring an array from PHP to JavaScript within a function

Having trouble accessing the array returned by a PHP function in JavaScript. Instead of seeing the actual array, I get the message: function Array() { [native code] } How can I retrieve and work with the items in the array? When I try using alert(pad ...

Triggering a function in response to a click

I'm encountering an issue with calling a callback inside a click event. Initially, I am attaching the click event to each table row. jQuery(tr).click(function (event) { var that = this; A(event, that, function () { var $gantt_containe ...

Click to Rotate Image Icon

I could use some assistance with this task. I want to create a functionality where clicking on the text/icon causes the + icon to rotate 45 degrees, resembling an x icon. With each subsequent click, the icon should alternate between the + and x shapes. An ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

Eliminate the need for index.html in the URL when using MVC WebApi

I am currently utilizing Angular for the front end and have an index.html page as the starting point. On the main page, the URL appears as follows: localhost:588/index.html#/ I desire it to appear as: localhost:3478/#/ or simply localhost:3478/ The iss ...

Can Google's bot initiate JavaScript click events on a website and how can this be resolved?

Currently, we are facing an issue with the reviews on our website. In order to optimize page load speed on both desktop and mobile, we have decided to initially display only 10 reviews. After each button click by the user, the next set of 10 reviews is loa ...

What is the process of integrating jQuery into a Chrome application?

I am trying to incorporate jQuery methods into my Chrome app, but I'm uncertain about the process of including the API. As someone who is new to front-end development, I am essentially looking for something similar to .h #include, which I typically us ...

Remove the JSON object by comparing IDs between two JSON objects in JavaScript or Node.js, deleting it if the ID is not found

let data = fetchData(); let anotherData = getAnotherData(); let result = data.reduce((accumulator, current) => { if (!accumulator[current.system.name]) { accumulator[current.system.name] = {}; } let detailsObject = {}; Object.keys(current. ...

What is the best way to utilize Python in order to transform a large amount of unicode into characters to create a string-like appearance?

In JavaScript, I've managed to do this: eval(String.fromCharCode(102,117,110,99,116,105,111,110,32,99,104,101,99,107,40,41,123,13,10,09,118,97,114,32,97,32,61,32,39,100,52,103,39,59,13,10,09,105,102,40,100,111,99,117,109,101,110,116,46,103,101,116,69 ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

What is the method to retrieve a javascript object from within a string template?

I am trying to find a way to map data from an object into a string template using JavaScript. Here is an example of the string and object I am working with: const menu = { breakfast: { description:'something' } meal: { d ...

Only the initial setInterval function is currently active, despite multiple being set simultaneously

I am currently working on developing a webpage with a dynamic background featuring moving clouds. The code I have written for this project utilizes jQuery as shown below. browserWidth = 0; browserHeight = 0; clouds = 4; cloudSpeed = 50; $(function() { ...

Verify whether a variable is empty or not, within the sequence flows in Camunda Modeler

When working with a sequenceFlow in a process instance, I need to check a condition that may involve a variable that has not been defined yet. I want the flow to proceed even if the variable is not defined, rather than throwing an ActivitiException. I hav ...

What distinguishes passing an event handler directly versus encapsulating it within an arrow function in React?

Are there any distinctions in how these 2 inputs utilize the event handler in terms of functionality or performance? export default function App() { const handleChange = e => { console.log(e.target.value); } return ( <div className=& ...

Transfer files using Ajax and FormData technique

I have extensively researched various topics on this issue and prefer not to rely on any external plugins. function addToDatabase(menuItem){ var formData = new FormData(); formData.append("Description", document.getElementById("DescriptionID").value); ...

Slimming down AngularJS with minification

UPDATE 3: The issue was not related to dependency injection but rather with angular-mock. Refer to the response from 'Pierre Gayvallet' below. I prefer not to use ngmin, ngAnnotate, or any other grunt plugin when minifying my code. Instead, I u ...

Angular 4 or React: Unveiling the Performance Battle between Theory and Reality

While it may seem like the same old comparison between x vs y, what is faster?, I believe my version offers a unique perspective. React and Angular are as different as GTK and Qt (or even more), making comparisons between them futile - one is a versatile f ...