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

房东的猫 提交于 2021-02-18 22:12:20

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/44887015/angular-2-google-maps-get-coordinates-from-click-position-on-map-to-update-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!