Using Angular to load Google Maps API upon webpage opening

Struggling to integrate lat/long data from the user's location into the Google Maps API upon page load and facing an injection error. Being new to Angular, still grappling with understanding how scope functions, so any help is appreciated.

The main file app.js exists in a top-level directory:

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

In the controllers directory, the main controller calls a getZip function as shown below:

app.controller('ForecastController', ['$scope', 'forecast', function($scope, forecast) {
  $scope.getZip = function(){
    forecast.getZip($scope.zipFinder).then(function(response){
        $scope.response = response.data;
    });
  }
}]); 

Additionally, there is a separate file named getLocation.js that retrieves lat/long data through the navigator:

function getLocation(position) {
  navigator.geolocation.getCurrentPosition(getLocation);
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;
  var $latlng = lat + "," + lng; // Questioning if this variable will carry over to the factory
} 

There is also a factory file where attempts are made to include the lat/lng data in an http.get request for the API. Unsure of how to access the latlng variable here and considering whether the factory is necessary at all:

app.factory('forecast', ['$http', function($http) {
  function getZip(zipFinder) {
    $http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + $latlng + '&key=XXXXXXXXXX')
      .success(function(data){
        return data;
      })
  }
}]);

The HTML setup:

<body onload="getLocation()" ng-app="ForecastApp">
  <div ng-controller="ForecastController">
    <div class="zipFinder" ng-model="zipFinder">
      <h3>Your zip code is {{ zipFinder.result_type | postal_code }}</h3>
    </div>
  </div>
</body

Exploring options on combining the getLocation.js and the factory to bring the latlng variable into scope but struggling to achieve success. Seeking assistance on finding a solution to link these two components together.

Appreciate any help.

Answer №1

Check out this demo showcasing the integration of Google Maps API in an AngularJS project:

http://plnkr.co/edit/34dcQZxHydMI9fFpj8Aq?p=preview

The MainCtrl's getMyAddr() function demonstrates the utilization of geolocation and geocode APIs seamlessly without requiring a new factory:

  $scope.getMyAddr = function() {
    navigator.geolocation.getCurrentPosition(function(pos) {
      var latlng = pos.coords.latitude +","+ pos.coords.longitude;
      console.log('geolocation: '+latlng);
      $http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng) // + '&key=XXXXXXXXXX')
        .success(function(data){
          console.log('geocode: ', data);
          $scope.results = data.results;
          if (!$scope.$$phase) $scope.$apply();
        });
    }, function(error) {
      alert('Unable to get location: ' + error.message);
    });

}

Answer №2

After much trial and error, I finally found a solution that actually works. It turns out I was overthinking things.

Here's the JavaScript code snippet:

app.controller('ForecastController', function($scope, $http) {
  $scope.getLocation = function() {
    // extracting location info from the browser
    navigator.geolocation.getCurrentPosition(function(pos) {
    var latlng = pos.coords.latitude +","+ pos.coords.longitude;
    // using the GMaps API to retrieve data based on location
    $http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng + '&key=XXXXXXXX')
    .success(function(data){
      $scope.results = data.results;
      $scope.quantity = 1;
    });
  }
});

And here's the HTML code snippet:

<div ng-init="getLocation()">
  <div ng-repeat="result in results | limitTo:quantity">
    <h2>Your zip code is {{ result.address_components[7].long_name }}</h2>
  </div>
</div>

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

Bootstrap Django Table Paginating

Having some difficulty implementing table pagination in a django-bootstrap project. The bootstrap's table pagination feature is not displaying on my template as expected. I am using one of the default bootstrap tables with custom styles, and seeking a ...

In Chrome, there is a flicker in the jQuery animated fade out before the callback function is triggered

I created a small feature that allows users to click on a text element, causing it to animate and fly to a specific location before disappearing. Check out this demo of the functionality. Below is the code snippet from the click handler (written in coffe ...

JavaScript Array Problem

Could you please review the code below and help me understand why I am encountering issues when trying to run the program? $(document).ready(function() { var comp = new Array("AAPL", "MSFT", "XRTX&"); var t = setInterval(function(){ ...

What is the best way to highlight excess characters in Kendo UI Editor by setting the selectedRange, similar to Twitter's feature

Can anyone provide guidance on wrapping parts of the nodes in a Kendo UI Editor with a span when they exceed the character limit? I'm looking to replicate the feature in Twitter where excess characters are shown in red. Is there a way to adjust the s ...

Error message notifying user that an index is not defined in an ajax

https://i.sstatic.net/AbqOp.pngThis may appear to be a repetitive question, but I assure you it's not. Despite my efforts on Google, the bug persists. The problem lies in the php script's inability to set the $_POST array to the value passed by ...

What is the reason Applisten is executed before sequelize?

Why is the code not returning success before app listen as I expected? I don't understand how it works. Can someone explain why? sequelize .sync() .then(() => { console.log('successfull') }) .catch(err => {console.error(&a ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

Enhancing the speed at which Discord fetches usernames for numerous users using discord.js

Below is the code snippet: const memberGroup = ["801555002664419350", "801555002664419351", "801555002664419352", "801555002664419353", "801555002664419354", "801555002664419355", "8015550026 ...

Whenever I attempt to alter the text of a single button in the map using ReactJS, the change reflects on all buttons simultaneously

Currently, I am facing an issue while trying to create a map in React JS with buttons. When I click on a button, it changes the text of all buttons instead of just the specific one. I believe the problem lies in not specifying the button_id, but I am unsur ...

Bootstrap-datetimepicker - unexpectedly appears in the incorrect location due to dynamic addition

Upon writing to the database via ajax, my success function builds an element and appends it to the table. However, when calling a datetimepicker on the newly appended row, the calendar displays in an unexpected location. Refer to the screenshot for details ...

Create two tables using vanilla JavaScript

I am currently working on a program that randomly assigns Christmas gift-givers and receivers. To facilitate this, I have set up two arrays: Players[] and Players2[]. When a player is added, their name is pushed into both arrays. During the draw process, ...

Focusing in on the mouse location to magnify a THREE.js element

I am currently working on a project using THREE.js and I have encountered an issue with zooming the object. The zoom functionality is centered around the render position when using trackball controls, but I need it to be based on the cursor's position ...

Unlocking the secrets of text parsing

When retrieving a text field from a document using JQuery, it sometimes includes <em></em> or <cite></cite> tags that I want to remove in order to get the raw text. To retrieve the text by its id, I use the following code: $(' ...

Coordinating the retrieval of JavaScript files using both AJAX requests and the <script> tag

core.js: var core = { all:{}, load: function(jsUrl) { $.ajaxStup({async, false}); $.getScript(jsUrl); }, init: function () { $.getJSON('someurl', function(data) { for(key in th ...

Troubleshooting JavaScript Oscilloscope: resolving audio playback problems

I am exploring JavaScript for the first time and came across an interesting oscilloscope example on this GitHub page. It seemed quite easy to follow initially, but I am facing an issue with audio playback. Although the HTML5 audio element loads the audio f ...

Out of nowhere, my React App has decided to stop working despite no recent changes

Hi everyone, I recently forked a React app from https://github.com/conedex/frontend. It was working perfectly fine until it suddenly stopped with this error message: ./node_modules/@metamask/utils/node_modules/superstruct/dist/index.mjs 46:43 Module parse ...

Create test scenarios using a two-dimensional array

I am utilizing four arrays in creating various test cases, as demonstrated below: var phone = ['phone1', 'phone2', 'phone3']; var browsers = ['chrome', 'firefox']; var location = ['1324',' ...

Adjust the height of a div element and enable scrolling to fit the

There are numerous inquiries regarding this particular issue. I have exhausted nearly all possible solutions I could find, yet none of them delivered the desired outcome. This is the structure of my page: <div> <header id="status"> / ...

What are the steps to specifically target eval errors when using JSLint?

I am looking to specifically scan my JavaScript code for eval errors using JSLint, while allowing other errors. I understand that I can manually set each error type as "true" individually, but with so many options, is there a simpler way to achieve this? ...

Socket IO: Error - The call stack has exceeded the maximum size limit

Whenever a client connects to my node.js server, it crashes with a 'RangeError: Maximum call stack size exceeded' error. I suspect there's a recursive problem somewhere in my code that I can't seem to find. This is the code on my serve ...