Interactive map with AngularJS featuring dynamic markers and real-time updating of marker position

In my Angular application, I have integrated a Google Map with a marker. I am looking to make the marker move along with the map as it is being moved. Currently, the marker stays in its default position when the map is moved. How can I achieve the effect of moving the marker and retrieve its current position?

Here is the code snippet:

<div class="col-lg-5 col-md-5 col-sm-12 col-xs-10 col-lg-offset-2 col-md-offset-1" style="padding: 0">
                <div ng-if="!mapLoaded" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{map.url}}" style="width: 100%;height:100%">
                    <div ng-map center="{{map.center.latitude}},{{map.center.longitude}}" zoom="{{map.zoom}}" styles="{{ map.styles}}">
                    </div>
                </div>
                <div ng-if="mapLoaded" class="map-dialog-container">
                    <div ng-map center="{{map.center.latitude}},{{map.center.longitude}}" zoom="{{map.zoom}}" styles="{{ map.styles}}">
                    </div>
                </div>
            </div>

This is the controller logic:

$scope.map = {
                zoom: 8,
                center: {
                    latitude: 52.348763181988105,
                    longitude: 20.928955078125
                },
                url: 'https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap',

                NgMap.getMap().then(function (map)
            {
                var location = [52.348763181988105,20.928955078125];
                var infowindow = new google.maps.InfoWindow();

        var markerIcon = {
            url: 'resource/img/mapin.png',
            size: new google.maps.Size(32, 41),
            anchor: new google.maps.Point(0, 41),
            scaledSize: new google.maps.Size(32, 41),
            labelOrigin: new google.maps.Point(16, 55)
        };

                var latLng = new google.maps.LatLng(location[0],location[1]);
                var newMarker = new google.maps.Marker({
                position: latLng,
                map     : map,
                icon    : markerIcon
            });
                        console.log(newMarker.map);
            });

Answer №1

To keep track of the map's center movement, set up an event listener for the center_changed event. Ensure that the marker is always in sync with the map's center by updating its position accordingly.

Include the following JavaScript code snippet:

    map.addListener('center_changed', function() {

        newMarker.setPosition(map.getCenter());

    });

If you want to check the marker's current position, try this:

   console.log(newMarker.getPosition());

For a more precise output, you can use:

   console.log("Lat:" + newMarker.getPosition().lat() +
                "Lng:" + newMarker.getPosition().lng());

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

Reorganizing JSON Information

Currently, I am dealing with a JSON file that contains multiple sets of data structured like this: {"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

Error: Property '$filter' is not defined and cannot be read

Whenever a user clicks on a link, I display the json object on the UI. However, an exception is being thrown with the following message: TypeError: Cannot read property '$filter' of undefined Check out the demo here: http://plnkr.co/edit/5NOBQ3 ...

How can I use jQuery to target elements other than the vertical scrollbar when

Here is how I am utilizing the mouseleave jquery event $(document).ready(function(){ $(document).mouseleave(function(event) { //perform a task }); }); Is there any method to prevent this event from triggering when a user scrolls ...

Pre-rendering Vue.js for SEO with prerender-spa-plugin becomes unresponsive during the npm run build process

My current issue arises when attempting to execute the command npm run build while utilizing the pre-rendering plugin in my webpack configuration. I incorporated some advanced options in webpack such as: `captureAfterDocumentEvent: 'fetch-done' ...

Creating a dynamically changing AppBar component in material-ui-next React that responds to scroll events

Following the Material Design guidelines, the top app bar should exhibit specific behavior: When scrolling, the top app bar can [...] undergo the following changes: - Scrolling upwards hides the top app bar - Scrolling downwards reveals the top ...

Is there a way to retrieve the dates from last month using jQuery?

Currently, I am unable to select past dates with the provided code. How can I adjust it to allow for selecting dates from previous months? let firstDay = new Date(); $('#date_filter_startmonthly').datepicker({ startDate: firstDay, endDate: ...

Angular JS: Grabbing Text from a Specific div and Copying it to Clipboard

I recently developed a Random Password Generator using Angular JS. Here is how the output appears in the application: <div data-ng-model="password" id="password"> <input class="form-control" data-ng-model="password" id="password" placeholder=" ...

Tips for programmatically choosing images from a Google Photos collection?

Currently, I am attempting to use code in the console to automatically choose a photo from a Google Photos Album while browsing. I've tried this method so far: const photo = document.getElementsByClassName('p137Zd')[0].parentElement photo. ...

Dealing with issues of toggling visibility with jQuery when using a dropdown menu

Inside a hidden drop down div, the focus is on "DC" right now. In the image below, we are looking at sales: HTML: <td class="edit"> <select class="touch" style="display: none;"> <option value="11">Rebuying</option><option value ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

javascript utilizing the canvas feature to resize and add graphics to an image

Is it possible to leverage Canvas for drawing over images that have been downloaded by users, all while adjusting the scale? For instance: User uploads an image Starts drawing on the image Zooms out and continues adding more drawings All modifications ...

Problem with bcrypt npm installation on Mac OS X 10.9 and Node v0.10.22

Operating System Information: Mac OS X 10.9 Node version: v0.10.22 An error occurs when attempting to install the bcrypt package. Any suggestions on how to resolve this issue? Any assistance would be highly appreciated. > [email protected] install /U ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

What is the best way to create dynamic .env files that can easily adapt to different environments instead of

Having multiple .env files (one for Vue and one for Laravel) with 'localhost' hard coded in them is causing accessibility issues from other computers on my network. It would be beneficial to have this set up dynamically, except for production. F ...

Locating every quadrilateral within a mesh

I'm currently using Three.js to load a mesh and I am attempting to texture each quad individually. At the moment, I am able to texture each face (triangle), but I am unsure of how to determine if the current triangle and the last triangle are part of ...

What is the best way to access an excel file using JavaScript and Protractor?

Is it possible to read an Excel file dynamically in JavaScript and iterate through cell values using row and column counts, without converting it into a JSON object? I have searched through several posts on Stack Overflow but have not found a solution yet. ...

Stepper wizard experiences a variation in CSS styling when minified

Two plunkers showcasing material design wizard selectors are causing different behavior upon stepper clicks. One uses a minified version of CSS while the other is expanded. The issue arises with the transition effects in the .step-wizard .progressbar class ...

What is the method for making an API call in AngularJS that includes sending a .pfx file?

I am currently working on integrating a Bank API and need to send a file along with the request. I was able to configure the certificate and password in Postman, which allowed me to connect successfully. However, in my Angular project, I am facing challeng ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...