Unresolved Issue: AngularJS Integration with Google Maps Marker Display Problem

My marker is working fine on $scope.mapCreated, but when the user clicks on $scope.centerOnMe(), only the current location is displayed without the marker.

Should I refer to this example or is there a simpler solution?

controller

.controller('mapCtrl', ['$scope', '$state', '$ionicLoading', function($scope, $state, $ionicLoading){

$scope.mapCreated = function(map) {

    var latlngPlace = new google.maps.LatLng(-27.4264356, -51.7838787);
    var marker = new google.maps.Marker({
        map: map,
        position: latlngPlace
    });

    $scope.map = map;
};

$scope.centerOnMe = function () {
console.log("Centering");
if (!$scope.map) {
  return;
}

$scope.loading = $ionicLoading.show({
  content: 'Wait...',
  showBackdrop: false
});

navigator.geolocation.getCurrentPosition(function (pos) {
  console.log('Got pos', pos);

  $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));

    var myPlace = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

    var marker2 = new google.maps.Marker({
        position: myPlace
    });


  $ionicLoading.hide();

}, function (error) {

    console.log('Error' + error.message)
});
};    

}])

directives.js

angular.module('app.directives', [])

.directive('map', function(){

return {
restrict: 'E',
scope: {
  onCreate: '&'
},
link: function ($scope, $element, $attr) {
  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-27.426102, -51.784999),
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map($element[0], mapOptions);

    $scope.onCreate({map: map});

    // Stop the side bar from dragging when mousedown/tapdown on the map
    google.maps.event.addDomListener($element[0], 'mousedown', function (e)  {
      e.preventDefault();
      return false;
    });
  }

  if (document.readyState === "complete") {
    initialize();
  } else {
    google.maps.event.addDomListener(window, 'load', initialize);
  }
}
}

});

map.html

<ion-view title="Map" id="page9" style="background-color:#FFFFFF;">
<ion-content>
    <map on-create="mapCreated(map)"></map>
</ion-content>
<ion-footer-bar class="bar-stable bar-calm">
  <a ng-click="centerOnMe()" class="button button-icon icon ion-navigate">FindMe</a>
</ion-footer-bar>
</ion-view>

Answer №1

One method to add a new marker is by utilizing the centerOnMe() function. An example of how this can be accomplished is provided below. This is the sole approach for creating a new marker.

$scope.centerOnMe = function () {
  console.log("Centering");
  // Adding a new marker
  var marker1 = new google.maps.Marker({
    map: $scope.map,
    position:  new google.maps.LatLng(lat, lng);
  });

  if (!$scope.map) {
     return;
  }
}

Answer №2

The essential element that was absent is the map: $scope.map

var location = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

var pin = new google.maps.Marker({
    map: $scope.map,
    position: location
});

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

Issues encountered while working with dynamic content in fluentlenium

While conducting tests using fluentlenium on my application, I encountered some errors. I am utilizing Play Framework and Slickgrid to generate my grid. Slickgrid dynamically creates the grid in javascript. The structure of the grid that is generated looks ...

.click function failing to trigger on dynamically loaded form

I'm facing an issue with a form that displays images from my database. After retrieving the filepaths, they are loaded dynamically into the form along with a "Delete" <button> for users to delete the image via AJAX. Although I can successfully ...

Link to a completely random webpage

I am looking to add a randomization feature to my collection of 30 HTML pages. When a user clicks on a button, I want one of the 30 pages to be displayed randomly. I have come across some scripts online that claim to achieve this, but they seem a bit mess ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Utilize the data-toggle attribute to retrieve a unique variable name, which can then be integrated into a function for added

I'm in the process of replacing an iframe with an image, and I want to accomplish this with minimal code. The container div I'm working with has a data-toggle attribute: <div id="my-div" data-toggle="video2"> <div id="videocontaine ...

Combining text shapes in Three.js without losing their distinct material colors

Currently experimenting with merging text geometries in Three.js (r84) and looking to achieve this using multiMaterial while preserving individual colors for each text object. Check out the live demo here: https://jsfiddle.net/5oydk6nL/ Appreciate any ins ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

Automatically populate dynamic fields with ajax response

Using auto-fill with an ajax request works well for static fields. For example: $this->registerJs("$(document).delegate('.form-control','change',function(event){ $.ajax({ url: '".yii\helpers\Url::toRoute( ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

Troubleshooting guide for resolving parse error when installing Open MCT

Hi there! I'm currently in the process of installing NASA's Open MCT (Link) but have hit a roadblock with errors during installation. Upon running npm install, I encountered the following error message: { Error: Parse error using esprima for fil ...

Using jquery to remove textbox value when checkbox is unchecked

I have a single datatable created using jQuery. The first column of the table consists of checkboxes, and the last column contains textboxes. Because these elements are generated dynamically, they end up having identical IDs and names as shown below: $ ...

Leveraging the power of Angular's ng-repeat for iterating through multi-dimensional arrays

Currently, I am in the process of developing a game and utilizing NG repeat to dynamically insert divs based on the number of letters and words present. For instance, if the answer to a question in the game is "Clean Sheet," I would like NG-Repeat to gener ...

How can I retrieve a specific number of documents from a database using GraphQL?

I'm looking to create a query in my GraphQL API that retrieves a range of documents, for example fruits(0:30), which would return 29 fruit-related documents from the collection. While I have experience querying documents in graphql using TypeScript, I ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

AngularJS directive encounters an error when trying to read the property 'childNodes' of undefined, resulting in a TypeError

I have created a custom directive called "Tab Slide Out" in AngularJS. Here is the code snippet: angular.module('myApp',[]).directive('tabSlideOut', ["$window", "$document", "$timeout", function($window, $document, $timeout) { // de ...

Where should AJAX-related content be placed within a hyperlink?

When needing a link to contain information for an AJAX call, where is the correct place to include the info? I have typically placed it in the rel attribute, but after reviewing the documentation for rel, it appears that this may not be the right location ...

Managing and updating arrays in VueJS2: Conditionally push new items and update only if their properties have changed

I am currently facing an issue with my form where each time a user updates a value in an input field, a new array element is created and added to the form results. I'm looking for a way to update the properties of the existing array element without cr ...

Drag and release: Place within invalid drop areas

I'm currently developing a drag-and-drop web application using Vue.JS and Vuex Store. The drag-and-drop functionality is based on the HTML Drag and Drop API as outlined in the Mozilla documentation. I have successfully implemented the Dropzone Compone ...

Error: The property 'length' cannot be read because it is undefined

I am currently in the process of creating a contact list organized by the first letter of each contact's last name. Once an ajax request is successful, the contact is added to the addContact function: Ajax success: ko.utils.arrayForEach(dataJS. ...

Implementing react-datepicker with redux-form

Having trouble integrating react-datepicker with redux-form and encountering an error message when selecting a date from the date picker: Uncaught TypeError: t.isSame is not a function Here is the code snippet: // Component utilizing date picker const r ...