Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ Google Maps get coordinates from click position on map to update marker position

I want to do something which is probably really simple however I can't seem to figure it out.

I integrated the Angular2+ Google Maps module to my Angular project (https://angular-maps.com/). Now I want to be able to replace the marker by clicking somewhere on the map. In order to do this I need to fetch the coordinates of the location where the user clicked on the map. If I have these coordinates I can update the longitude and latitude to move the marker. However I am not sure how to fetch the clicked location.

This is my map implementation in the html document:

<agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom" [streetViewControl]="false" [mapTypeControl]="true" [fullscreenControl]="true" (mapClick)="placeMarker()">
   <agm-marker [latitude]="latitude" [longitude]="longitude" [iconUrl]="'assets/geomarker.png'"></agm-marker>
   <agm-circle [latitude]="latitude" [longitude]="longitude" [radius]="20" [fillOpacity]="0.50" [fillColor]="'#00A19A'"></agm-circle>
</agm-map>

I am using the mapClick output event. (https://angular-maps.com/api-docs/agm-core/components/AgmMap.html) However this event does not seem to emit any coordinates. I am cathing the event like this right now:

placeMarker(){
  console.log(event);
}

And this is the output:

MouseEvent {isTrusted: true, screenX: 3657, screenY: 67, clientX: 401, clientY: 318…}
altKey
:
false
bubbles
:
true
button
:
0
buttons
:
0
cancelBubble
:
false
cancelable
:
true
clientX
:
401
clientY
:
318
composed
:
true
ctrlKey
:
false
currentTarget
:
null
defaultPrevented
:
false
detail
:
1
eventPhase
:
0
fromElement
:
null
isTrusted
:
true
layerX
:
364
layerY
:
154
metaKey
:
false
movementX
:
0
movementY
:
0
offsetX
:
364
offsetY
:
154
pageX
:
401
pageY
:
318
path
:
Array(23)
relatedTarget
:
null
returnValue
:
true
screenX
:
3657
screenY
:
67
shiftKey
:
false
sourceCapabilities
:
InputDeviceCapabilities
srcElement
:
div
target
:
div
timeStamp
:
18285.225000000002
toElement
:
div
type
:
"click"
view
:
Window
which
:
1
x
:
401
y
:
318
__proto__
:
MouseEvent
like image 509
Marijn van der Steen Avatar asked Jul 03 '17 13:07

Marijn van der Steen


1 Answers

I have found the answer myself.

On the HTML side I had to use:

(mapClick)="placeMarker($event)"

And on the typescript side I had to use:

  placeMarker($event){
    console.log($event.coords.lat);
    console.log($event.coords.lng);
  }

This returns the latitude and lontitude individually, now I can push these coordinates to the marker in the HTML file to update its location.

like image 139
Marijn van der Steen Avatar answered Oct 23 '22 00:10

Marijn van der Steen