Using Angular5 to extract coordinates from the Google Maps v3 API when a map "click" event occurs

Can anyone assist me with retrieving coordinates from a click event on a map?

Here is the desired result: Link

Below is the code I have so far:

import { Component, OnInit } from '@angular/core';
import { ViewChild } from '@angular/core';
import { } from '@types/googlemaps';
import { map } from 'rxjs/operator/map';
import { Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-google-map',
  templateUrl: './google-map.component.html',
  styleUrls: ['./google-map.component.css']
})
export class GoogleMapComponent implements OnInit {
  constructor() { }

  markers: Array<Object>
  myLatLng = { lat: 53.131083, lng: 23.154742 };
  latitude: 53.131083;
  longitute: 23.154742;
  googleMap: google.maps.Map;

  ngOnInit() {
    var mapCanvas = document.getElementById("map");
    var myCenter = new google.maps.LatLng(53.131083, 23.154742);
    var mapOptions = {
      center: myCenter,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.googleMap = new google.maps.Map(mapCanvas, mapOptions);
    google.maps.event.addListener(map, 'click', function (event) {
      this.placeMarker(event);
    });
  }

  placeMarker(event) {

    //-------------- Unable to retrieve map coordinates -------------
    var eventLatLng = { lat: event.clientX, lng: event.clientY };
    console.log(eventLatLng);
    var marker = new google.maps.Marker({
      position: this.myLatLng,
      map: this.googleMap
    });

    var infowindow = new google.maps.InfoWindow({
      content: 'Marker Location:' + marker.getPosition()
    });

    infowindow.open(this.googleMap, marker);
  }

  addBicycleLayer() {
    var bikeLayer = new google.maps.BicyclingLayer();
    bikeLayer.setMap(this.googleMap);
  }

  setMapType(mapTypeId: string) {
    this.googleMap.setMapTypeId(mapTypeId)
  }


  setCenter(e: any) {
    e.preventDefault();
    this.googleMap.setCenter(new google.maps.LatLng(this.latitude, this.longitute));
  }
}

HTML component:

<div id="map" style="width:100%;height:600px" (click)="placeMarker($event)">
</div>

I am struggling to obtain the map coordinates. The ones in the placeMarker function are just client coordinates and not integrated with Maps. I came across this but it seems like a big project and I prefer not to rely on it. Any help would be greatly appreciated :)

Cheers

Answer №1

Thanks to the assistance from Jags, I was able to find the solution I needed! Below is the complete and functional code snippet:

import { Component, OnInit } from '@angular/core';
import { ViewChild } from '@angular/core';
import { } from '@types/googlemaps';
import { map } from 'rxjs/operator/map';
import { Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-google-map',
  templateUrl: './google-map.component.html',
  styleUrls: ['./google-map.component.css']
})
export class GoogleMapComponent implements OnInit {
  constructor() { }

  markers: Array<Object>
  myLatLng = { lat: 53.131083, lng: 23.154742 };
  latitude: 53.131083;
  longitute: 23.154742;
  googleMap: google.maps.Map;

  ngOnInit() {
    var mapCanvas = document.getElementById("map");
    var myCenter = new google.maps.LatLng(53.131083, 23.154742);
    var mapOptions = {
      center: myCenter,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.googleMap = new google.maps.Map(mapCanvas, mapOptions);
    google.maps.event.addListener(this.googleMap, 'click', (event) => {
      this.placeMarker(event);
    });
  }

  placeMarker(event) {

    var marker = new google.maps.Marker({
      position: event.latLng,
      map: this.googleMap
    });
    console.log(event.latLng.lat() +" "+ event.latLng.lng());
  }

  addBicycleLayer() {
    var bikeLayer = new google.maps.BicyclingLayer();
    bikeLayer.setMap(this.googleMap);
  }

  setMapType(mapTypeId: string) {
    this.googleMap.setMapTypeId(mapTypeId)
  }


  setCenter(e: any) {
    e.preventDefault();
    this.googleMap.setCenter(new google.maps.LatLng(this.latitude, this.longitute));
  }
}

You can find a visual representation of the working code here :)

Answer №2

Remove the `(click)="placeMarker($event)"` as it's not the action you want to take.

Instead of logging `this` in the click event, try using the fat arrow function to pass the correct context to your function.

google.maps.event.addListener(this.googleMap, 'click', (event) => {
  this.placeMarker(event);
});

Now, you should have the correct `event` in the `placeMarker` function, allowing you to access the latlng from the `event`.

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

Prevent the default scroll event triggered by the mousewheel in certain situations. It is not possible to use preventDefault within a passive event

I have a div element with the onWheel attribute. By default, the browser interprets onWheel as scroll behavior. However, I want to prevent the browser's default mouse behavior under certain conditions. Unfortunately, I encountered an error that say ...

The onBlur() method is not functioning properly in JavaScript

Created a table using PHP where data is fetched from a MySQL database. One of the fields in the table is editable, and an onBlur listener was set up to send the edited data back to the MySQL table. However, the onBlur function doesn't seem to work as ...

Sending PHP variable to jQuery using POST

To keep track of page referrals, I often use URLs like this: www.example.com/?ref=google Once I've captured the referral as a variable, it looks like this: if ($_GET['ref'] !== "") { $ref = $_GET['ref']; } else { $ref = ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

Next.js 13 app directory experiences 404 Not Found error due to dynamic routing issues

I recently built a straightforward to-do app using Next.js 13 paired with TypeScript. The process involved creating an array of objects, each comprising an id string and a name string. Subsequently, I iterated through the list and showcased the names withi ...

Utilize the reducer from another slice in Redux Toolkit

I am working with an authSlice const authSlice = createSlice({ name: 'authStore', initialState, reducers: { logout(state = initialState) { return { ...state, isAuthenticated: false }; }, }, extraReducers: (builder) => { ...

There was an issue with the layout detection in Angular. The app-layout selector could not find a matching element in the code

Currently diving into the world of Angular and embarking on my first project, I've hit a roadblock. After initiating a terminal with the server, all I get is a blank page when I load my browser. Upon inspecting the page using f12, an error message pop ...

Connecting Angular TextArea functionality to the Ctrl-Enter keyboard shortcut

Recently, I've been working on creating a custom functionality for the <textarea> element. My goal is to have the enter key trigger a specific function, while using ctrl+enter will add a new line in the textarea. I've tried looking through ...

How can I incorporate an interface and specify a particular type as the return value in TypeScript?

interface Inter{ str:string } function func(){ let v:Inter={ str:'abc' }; return v; } func()//Is there a way to ensure that the type of value returned from `func` is {str:'abc'} without explicitly declaring it i ...

Exploring the integration of Formik with Material-UI's select field - A step-by

Trying to implement Formik with Material-UI's Textfield component using the select attribute. Every time I change the option, it shows this warning: Material-UI: You have provided an out-of-range value null for the select (name="subIndicatorId& ...

Encountering an unexpected error when attempting to make a REST service call using Angular

Trying to retrieve JSON data from a REST service in my Angular 8 application using a GET call with parameters including link, authorization: basic, username, and password. When testing the call in Postman, it returns the expected data without any issues. H ...

DataGrid parameters in Material UI are only considering the final value in the table

I am working with a Data Grid table containing user information, and I want to include a sub-menu of options in the last column that opens up a modal for each user. However, I am facing an issue where only the data from the final row in the table is being ...

Tips for preventing Unknown event codes in POST request responses

When my client makes POST requests to the nodejs server I am running, I receive "unknown event 72" messages in the POST response, as shown in the Wireshark screenshot below. These extra data points are causing unnecessary bandwidth usage for my application ...

Ways to conceal and reveal image and text elements based on array loop output

I am currently working on setting up a questionnaire. The questions and answer options are being pulled from a database using an API. Some of the options include images, with the image link stored in the database. I am trying to find a solution where text ...

Messages are not showing up inside the repeater

I developed a custom directive that displays blank input fields to be filled with project names in an array of objects. Each object has multiple properties, but for now, I am focusing on the project name property only. <div ng-repeat="projectStatus in ...

Using PHP to send variables to an AJAX function via parameters

I've encountered an issue while attempting to pass 4 variables through the parameters of the ajax function. The variables I'm trying to pass include the URL, action, ID, and timeout in milliseconds. Unfortunately, the function is not accepting th ...

Guidelines for importing dependencies of nested components in Angular 6

I am currently in the process of creating two components: Configuracion and Equipo. The setup for these components is located in configuracion.component.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular ...

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...