"An issue with geolocation is causing it to be unable to locate

Incorporated a map into my AngularJS/Ionic application using geolocation with a "find me" feature designed to identify our location on the map. However, encountering issues in implementing this functionality - the progress circle displays but fails to pinpoint my exact location.

JavaScript:

.controller('MapCtrl', function($scope, $ionicLoading, $compile, $state, $ionicPlatform, $location) {


    $scope.map = map;


    $scope.basel = {
        lat: 6.802107,
        lon: 79.921749
    };


    $ionicPlatform.ready(function() {
        navigator.geolocation.getCurrentPosition(function(position) {



            $scope.gotoLocation(6.802107, 79.921749);

            $scope.$apply();
        }, function(e) {
            console.log("Error retrieving position " + e.code + " " + e.message)
        });


        $scope.gotoLocation = function(lat, lon) {
            if ($scope.lat != lat || $scope.lon != lon) {
                $scope.basel = {
                    lat: lat,
                    lon: lon
                };
                if (!$scope.$phase) $scope.$apply("basel");
            }
        };

        for (var i = 0; i < $scope.locations.BranchAndAtms.length; i++) {

            var objectMark = $scope.locations.BranchAndAtms[i];
            $scope.whoiswhere.push({
                "name": objectMark.outlet,
                "lat": objectMark.lat,
                "lon": objectMark.lon,
                "date": objectMark.address
            });


        };

        for (var i = 0; i < $scope.locationsIDC.IDC.length; i++) {

            var objectMark = $scope.locationsIDC.IDC[i];
            $scope.whoiswhere.push({
                "name": objectMark.outlet,
                "lat": objectMark.lat,
                "lon": objectMark.lon,
                "date": objectMark.address
            });


        };

    });

  
    //google.maps.event.addDomListener(window, 'load', initialize);

    var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
    var compiled = $compile(contentString)($scope);



    $scope.centerOnMe = function() {

        if (!$scope.map) {

            return;

        }

        $scope.loading = $ionicLoading.show({

            content: 'Getting current location...',
            showBackdrop: false

        });
        window.alert("dgdfd");

        navigator.geolocation.getCurrentPosition(function(pos) {
                window.alert(pos);
                $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
                window.alert(pos.coords.longitude);
                window.alert(pos.coords.latitude);
            },
            function(error) {
                alert('Unable to get location: ' + error.message);
            });
    };

    $scope.clickTest = function() {
        alert('Example of infowindow with ng-click')
    };

})

HTML:

<div id="map" style="width:100%; height:100%; padding:10px; margin-top:45px;" ng-show="demo == 'ios'">

            <app-map style="height:100%; width:100%;"
            center="basel"
            zoom="3"
            markers="whoiswhere"
            > 
            </app-map>


    </div>

 <ion-footer-bar class="bar-dark">
      <a ng-click="centerOnMe()" class="button button-icon icon ion-navigate">Locate the nearest Branch</a>
    </ion-footer-bar>

Answer №1

To integrate this feature, add the following code snippet to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Answer №2

Instead of relying on Angular and the Google Maps API, I have opted for vanilla JavaScript to handle geolocation. Here is the code I used:

if (navigator.geolocation) {

    function success(geoposition) {
        var userLocation = new google.maps.LatLng(geoposition.coords.latitude, geoposition.coords.longitude);
        map.setCenter(userLocation);
    };

    function error(error) {
        console.warn('ERROR(' + error.code + '): ' + error.message);
    };

    var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 10000
    }

    navigator.geolocation.getCurrentPosition(success, error, options);

}

In your initial (success) function, you had the argument 'position' but it seems like you forgot to utilize it in order to obtain the user location. To do this, remember to extract position.coords.latitude and position.coords.longitude. Additionally, consider wrapping the function in an 'if' clause in case geolocation support is not available.

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

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

The controller's AngularJS function seems to be unresponsive

Issue with AngularJs ng-click Event I'm attempting to utilize the GitHub Search-API. When a user clicks the button, my Controller should trigger a search query on GitHub. Here is my code: HTML: <head> <script src="js/AngularJS/angula ...

Display a single item using Jquery when clicking on an element with the same class

I'm relatively new to JQuery/Javascript scripting and I'm having some difficulty. How can I display one item with the same class without affecting the other items? Here is my code: $(function() { $('.embedContainer > .myPosterImage& ...

Can other JavaScript event listeners be synchronized with an asynchronous event?

My goal is to manipulate a web page using Tampermonkey where there is a button with certain event listeners followed by a redirect. Is it possible for me to insert my own click event handler into the button, which triggers an AJAX request and waits for it ...

Sending a message from a Vue.js application to Contact Form 7 using the Wordpress REST API - a step-by-step guide

I recently added Contact-Form-7 to my WordPress admin panel, which generated an API Endpoint for me at http://localhost/wordpress/wp-json/contact-form-7/v1/contact-forms Attempting to send a POST request to this endpoint using the following code: data() ...

Tips for applying an active class to buttons using ng-click?

Here is the HTML code for the buttons. The taskfilter is the filter that controls how the buttons work when clicked and the class name is 'sel' <a class="clear-completed" ng-click="taskfilter = 1" ng-class="{'sel':enabled}"> &l ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

I'm looking for a method to trigger onChange() specifically on Internet Explorer using only JavaScript, HTML, and CSS without relying on jQuery

Looking for a way to utilize onChange() only on Internet Explorer using Javascript, HTML, CSS (No Jquery). My current code successfully sends the input to my function upon onChange(), but it seems to work smoothly on Chrome and not on IE. Is there a meth ...

What is the most effective way to divide input elements into an array in Angular?

How can I bind an input value to an ng-model as an array? For example, if I enter one, two, three, I want the resulting model to be [ "one","two","three" ]. Currently, this is my approach: <input type="text" ng-model="string" ng-change="convertToArra ...

Personalize your AngularJS filters by name and date

Hello fellow coders! I'm diving into the world of AngularJS and could really use some guidance ...

An ELIFECYCLE error was encountered during the production deployment process, resulting in error number

I am currently struggling with a perplexing issue and urgently need to resolve it, so any guidance would be greatly appreciated. My project is built using Laravel and Vue, with Docker managing the image container. The application is deployed on AWS. The ...

What are the steps for integrating a date and time picker bootstrap plugin?

Referencing a tutorial from http://www.w3schools.com/bootstrap/bootstrap_modal.asp: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <div id="myModal" class="modal fade" role= ...

Creating a dynamic TextField that updates on change using React JS

Hey there, I recently embarked on my React learning journey and encountered an issue while trying to dynamically pass data from a response to my TextField. It appears that the TextField is not editable as the onChange function does not seem to be working. ...

Changing the way Hook setState is used with arrays in React by leveraging Splice

Can anyone help me figure out why my array splice functionality is removing all items below the clicked item instead of just that one item? I tried creating a copy of the array to modify, but it's not working as expected. Any suggestions? export defau ...

Issue with displaying nested React Elements from Component

I am currently facing an issue with my Collection component, which is utilizing a sub-component called RenderCollectionPieces to display UI elements. Strangely, I am able to see the data for image.name in the console but for some reason, the UI elements ar ...

Is there a way to exclude the element from being displayed when using ngIf in AngularJS?

Is there a way in Angular to conditionally add an element to the DOM without having it always added, even when its evaluation is false? I am looking for an alternative method to ngIf. ...

Saving Information Using Express-Session

Imagine you need a user to input their email and then save it to be accessible across multiple web pages. Would it be considered a poor practice to store this email in the session object of express-session? For example: req.session.email = '<user ...

The Issue of Browsers Freezing or Crashing Due to Ajax Autocomplete

My current project involves implementing Ajax Autocomplete for jQuery and passing additional parameters. While the documentation provides guidance on how to achieve this, I've encountered an issue where attempting to use a value from another field cau ...

Troubleshooting Vue.js 2 Routing Issues: Difficulty Accessing Posts Variable

My first venture into Vue.js involves working with WP REST API. Initially, all my posts are displayed perfectly. However, when I attempt to integrate Vue-router, the component responsible for showcasing all the posts, 'home-post-list', breaks do ...

Issue with AjaxSetup overlapping with jqgrid

How can I set up global AJAX calls using ajaxsetup without interfering with the functionality of jqgrids on my website? I want to apply the code below to my AJAX calls, excluding those related to jqgrids. $.ajaxSetup({ type: "POST", contentType: ...