Tips on ensuring that the Google Maps marker remains in the center as you drag the map with the AGM component

I've implemented AGM (Angular Google Maps) in my Ionic Project to showcase Google Maps, and I'm looking to have the marker stay centered on the map even when it is dragged. Is there a way to achieve this with AGM? Please let me know if I have made any errors. Thank you.

Below is a snippet of my current implementation. I have utilized the dragend method as per the guidelines provided in the AGM Docs.

map.component.html

<agm-map
      #agmMap
      [style.height.px]="height"
      [latitude]="lat"
      [longitude]="lng"
      [zoom]="zoom"
      [usePanning]="true"
      (mapReady)="mapReady($event)"
    >
<agm-marker
        [iconUrl]="{
          url:
            'https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-512.png',
          anchor: { x: 14.5, y: 28 },
          scaledSize: {
            width: 30,
            height: 30
          }
        }"
        [latitude]="lat"
        [longitude]="lng"
        [markerDraggable]="true"
        (dragEnd)="markerDragEnd($event)"
      ></agm-marker>
</agm-map>

map.component.ts

setNewCenter(latitude, longitude) {
    this.lat = latitude;
    this.lng = longitude;
    this.getAddress(this.lat, this.lng);
  }
public mapReady(map) {
    map.addListener("dragend", () => {
      this.setNewCenter(map.getCenter().lat(), map.getCenter().lng());
    });
  }

Here's how the map looks after using dragend, you can view it here -> https://ibb.co/9qVcLN5

Alternatively, when utilizing drag instead of dragend, the outcome is like the following preview. https://i.sstatic.net/Ybdpu.gif

Answer №1

To ensure the marker stays at the center of the map, you can utilize the drag event.

<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Maintaining Marker Position in Google Maps</title>
        <style>
            #map{
                width:800px;
                height:600px;
                float:none;
                margin:auto;
            }
        </style>
        <script>
            function initMap(){
                const latlng=new google.maps.LatLng( 51.495072, -0.100319 );
                const options = {
                    zoom: 16,
                    center:latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                const map = new google.maps.Map( document.getElementById('map'), options );
                
                let marker=new google.maps.Marker({
                    position:latlng,
                    map:map
                });
                
                google.maps.event.addListener( map, 'drag', e=>{
                    marker.setPosition( map.getCenter() )
                });
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap'></script>
    </head>
    <body>
        <div id='map'></div>
    </body>
</html>

Check out this demo on Fiddle

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 with implementing Ajax with JQuery Treeview

I am a newcomer to JQuery and web development in general. My goal is to retrieve data from an XML file and construct an unordered list. I have successfully achieved this, and now I am attempting to incorporate the TreeView plugin for collapsible/expandable ...

The parsing of a date string in JavaScript is done with the timezone of

let userInputDate = "2019-05-26" // received from browser query e.g. "d=1&date=2019-05-26" let parsedDate = new Date(userInputDate) console.log(JSON.stringify(parsedDate)) output: #=> "2019-05-25T19:00:00.0000Z" Issue When the user's time ...

What happens when AngularJS encounters real-time polymorphism during runtime?

An intriguing report by the Financial Times discusses how Shape Security, a Google-backed venture, is using shape-shifting code to outsmart hackers. Real-time polymorphism could revolutionize cyber security, attracting investors from major tech companies l ...

Issues with Angular ng-bootstrap tabset component not functioning as expected

{ "name": "ModalWindow", "version": "1.0.0", "repository": { "type": "git", "url": "" }, "scripts": { "build": "webpack --mode production", "start": "webpack-dev-server --mode development --open" }, "license": "MIT", "depend ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

Animations within Angular components are being triggered even after the parent component has been removed from

When a child component has an animation transition using query on mat-table rows, hiding the parent component will now trigger the child animation. To see this in action, check out this reproduction scenario: https://codesandbox.io/s/intelligent-jasper-hz ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

Using jQuery to retrieve an XML file from the local file system without encountering any cross domain errors

While trying to set up a website to operate on the local file system and retrieve an XML file, I encountered access control origin errors: The error message "Origin null is not allowed by Access-Control-Allow-Origin" keeps popping up. I attempted switchi ...

What is the most effective method for combining data from two APIs into a single React table?

Looking to combine data from 2 separate APIs that both have pagination capabilities. What is the most efficient method to present the merged data in a table? The data needs to be joined based on their unique id, however one API provides fewer records tha ...

break LineSegment at specified location

Using the vertex positions provided below, I am creating a square using THREE.LineSegments (or even by a simple THREE.Line.) vertices: path.vertices = [ new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ), new THREE.Vector3( 10.6000061 ...

What is the process for generating a variable script within an HTML tag using document.write?

Here is the code snippet: <script>var posterimage=/images/videos/intro/iamge01.png;</script> <script>document.write('<video controls="controls" height="300" id="video-playlist" poster="VARIABLE" preload="none" src="video.mp4" wid ...

"What is the best way to execute a series of service calls in order

There is a need to make calls to 2 different services, with the second one relying on data retrieved from the first one. The initial service provides an array of objects containing category IDs, and for each ID, the second service is used to fetch associat ...

Fixing vulnerabilities in npm requires Angular 7, but implementing them in an Ionic 3 project may lead to further complications

I have a query related to my Ionic 3 project. Upon running npm audit, I found 10 vulnerabilities that need to be fixed. However, both fixes require Angular 7, and I am aware that Ionic 3 only supports Angular 5. My question is, is there a way to address t ...

The error message "The export named 'render' (which was imported as 'render') could not be found" appeared

Encountering an error when building a Vue project with TypeScript and Webpack, specifically the "export 'render' (imported as 'render') was not found" issue. Below is the full error code: export 'render' (imported as 'ren ...

PhantomJS reveals underlying jQuery bug

Currently, I am developing automated test scripts that require a headless browser (PhantomJS) to perform all DOM navigation and actions except for downloads. So, PhantomJS seems like the right choice. However, I am encountering errors when trying to use P ...

Can you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

Is there a more effective approach to managing an array of objects retrieved from an API call?

I'm attempting to extract an array of names from a JSON response that contains an array of objects, but I'm running into issues. When I try to print the array, it shows up empty. Is this the correct way to go about it? There don't seem to be ...

Limit the keys in TypeScript to only the elements of an array

Modified: Updating ID Types I have an array that contains the following values: const ids: number[] = [45, 56]; const obj: any = { 45: "HELLO", 56: "WORLD", }; I want to specify a type for my object to only allow values that are in my ids array. I ...