Using Ngmap to dynamically display markers using ng-repeat in JavaScript

In my project, I am utilizing the angularjs-google-maps directive for map functionality.

Below is a snippet of code demonstrating how markers are added to the map:

<map id="map" style="height:450px" zoom="4" zoom-to-include-markers='auto' center="{[{center.lat}]},{[{center.long}]}" on-center-changed="centerChanged()">
<marker id={[{$index}]} animation="DROP" ng-repeat="location in locations" position="{[{location.latitude}]},{[{location.longitude}]}" on-click="click()" title="Click to zoom"></marker> 
</map>

My challenge now is how to select these markers from a javascript function. When selecting a marker by ID, it returns as a DOM element instead of a Google Maps marker object as illustrated below:

<marker id="1" animation="DROP" ng-repeat="location in locations" position="10.0050407,76.3459498" on-click="click()" title="Click to zoom" class="ng-scope"></marker>

Is there a way for me to access markers initialized through ng-repeat as Google Maps marker objects within JavaScript?

Answer №1

To access the Marker object, you can utilize angular's scope feature. Without viewing your specific JS code, I recommend checking out the Angularjs-Google-Maps example. In this example, each marker can be accessed using $scope.map.markers[key], where $scope.map.markers represents the array of markers within your scope.

angular.module('myApp', ['ngMap'])
.controller('MarkerCtrl', function($scope) {
  $scope.points = [{lat:37.7699298, lng:-122.4469157}];
  
  $scope.addMarker = function(event) {
    var coordinates = event.latLng;
    $scope.points.push({lat: coordinates.lat(), lng: coordinates.lng()});
  }
  
  $scope.removeMarkers = function() {
    $scope.points = [];
  };

  $scope.displayMarkers = function() {
    for (var key in $scope.map.markers) {
      $scope.map.markers[key].setMap($scope.map);
    };
  };
  
  $scope.hideMarkers = function() {
    for (var key in $scope.map.markers) {
      $scope.map.markers[key].setMap(null);
    };
  };
});

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

Async/await transformation in Node.js

Attempting to implement async/await functionality in node js, inspired by a helpful example. However, encountering errors. Here is the code snippet: function* gotNews(response){ console.log("in gotNews"); str=''; res ...

Guide to incorporating navigation buttons (back and forward) in a modal box

I have successfully created image thumbnails and linked them using the provided code. <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script src="https://maxcdn.bootstra ...

Unclear error message encountered with Rails server

Currently using OS X Sierra I'm managing a rails app with front-end and back-end components. The back-end is built on rails 4, while the front-end utilizes Angular. To run the server locally for development or testing purposes, I typically need to ha ...

Inquiries about utilizing setTimeout with backbone.js and effectively managing timeouts

One of the questions I have is related to clearing timeouts using clearTimeout(content.idTimeout) for a specific idTiemout. But how can I clear all timeouts at once? Here is the model I am working with: var ContentModel = Backbone.Model.extend({ URL: "htt ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

"Following successful POST login and session storage in MongoDB, the session is unable to be accessed due

When sending login data by POST with the credentials: 'include' option from client server 5500 to backend server 3000, I ensure that my session data is properly stored in MongoDB thanks to the use of 'connect-mongodb-session'. In the ba ...

JavaScript error: Unable to access property `node` as it is null or does not exist

I'm currently working with ASP.NET 3.5, c#, and visual studio 2010. I have created a master file along with a default page that utilizes this master file. Within the master file, I've included a few asp:contentplaceholders and added corresponding ...

Obtaining the sum of two variables from two separate functions results in a value of NaN

Why is it that I'm seeing a NaN result when trying to access a variable in two different functions? This is my code var n_standard = 0; var n_quad = 0; var totalQuad; var totalStandard; var total = totalStandard + totalQuad; ...

What sets apart these two JavaScript namespaces?

My main goal is to expertly organize my javascript code by eliminating any global elements. I came across two namespace declaration methods in this informative post, and now I'm looking for your input on the advantages and disadvantages of each. ...

Is it possible to include a value for the "src" attribute rather than the "class" attribute in the array of values in list.js?

Check out the HTML code I wrote: <html> <head> </head> <body> <input class="search" placeholder="Search" /> <div id="users"> <ul class="list"> ...

Using orchestrate.js for local passport.js authentication

I need assistance finding a tutorial or resources for setting up local passport.js authentication with Orchestrate as the user storage. Most of the resources I have come across are based on MongoDB, but our project requires us to use Orchestrate. Any advic ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

Utilize AngularJS to effortlessly filter and search data

I am facing an issue with my AngularJS code for searching text. The rows in the table are not being displayed properly and the search functionality is not working effectively. <html ng-app="myModule"> <head> <title>TODO suppl ...

Effective methods for eliminating timezone in JavaScript

I need to display the time and format {{transaction.submitTime | date:'yyyy-MM-dd HH:mm:ss Z'}} Currently, it displays 2015-04-23 02:18:43 +0700 However, I would like to show the time without +0700, where the hour will be incremented by 7. Is ...

The initial ajax request successfully connects to the file, but encounters a 404 error upon the second attempt

I am currently encountering an issue with a jQuery post function. The function is designed to run multiple times and then stop, which it has successfully done in the past. However, now the problem arises when the function tries to execute itself again afte ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

Ways to prevent scrolling or switching to the next tab when my javascript function yields a false result

//HTML Code <div id="navigation1"> <ul> <li><a href="#"><input type="submit" value="Next" onClick="return checkfhname()" /></a></li> </ul> </div> Whenever my Javascript function checkfhname() r ...

When the Protractor configuration is executed, it displays the message "The requested webpage cannot be accessed."

Testing protractor on a vanilla.js app and encountering an error when running protractor basicConf.js The following error is occurring: This webpage is not available ERR_CONNECTION_REFUSED Here is the test script in use: describe('foo', fun ...

Transferring data to a web address

Utilizing a jax-rs endpoint, I am invoking a jsp page in the following manner. public String logout(@Context HttpServletRequest request,@DefaultValue("Empty Details") @QueryParam("logoutNotification") String logoutNotification, @Quer ...

Encountering "Unexpected token *" error when using Jest on an import statement

What could be the reason for Jest failing with the error message "Unexpected token *" when encountering a simple import statement? Error log: Admin@Admin-PC MINGW32 /d/project (master) $ npm run test > <a href="/cdn-cgi/l/email-protection" class="__ ...