Property 'coords' does not exist on type 'MouseEvent'. In Angular2-google-maps marker event

你。 提交于 2020-06-12 05:41:08

问题


I have added mapClicked event of angular2-google-maps map. The code is as below:

mapClicked($event: MouseEvent) {
this.markers.push({
  lat: $event.coords.lat,
  lng: $event.coords.lng,
  draggable: false
});

}

I am getting compile time error while serving my ionic 2 app with "ionic serve".

Thanks in advance, AB


回答1:


This is just Typescript complaining since the default MouseEvent interface doesn't have the coords property, but since you're using angular2-google-maps you know the coords property will be there (ng2 google maps MouseEvent interface) so you can avoid that compile time error by just using any instead of MouseEvent like this:

mapClicked($event: any) {
this.markers.push({
  lat: $event.coords.lat,
  lng: $event.coords.lng,
  draggable: false
});

EDIT

Just like @Bruno Garcia pointed out, a better way to solve this would be to import the proper interface from the AGM library. That way you could use typings and the autocomplete feature of the IDE for that MouseEvent event.

But instead of importing the MouseEvent as he described in his answer, I'd prefer to use an alias, to avoid any confusion with the default MouseEvent interface:

import { MouseEvent as AGMMouseEvent } from '@agm/core';

and then just use that alias:

mapClicked($event: AGMMouseEvent) { ... }



回答2:


The accepted answer is correct in pointing out that the default MouseEvent doesn't have a coords property.

But AGM does ship with its own MouseEvent interface which does contain a coords property of type LatLngLiteral as expected. You just need to import it:

import {MouseEvent} from "@agm/core";

Then TypeScript's warning will go away and you'll have typings for the $event argument.



来源:https://stackoverflow.com/questions/42453293/property-coords-does-not-exist-on-type-mouseevent-in-angular2-google-maps-m

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