Show markers in draggable Radius on Angular Google Maps

Google Maps can be easily implemented in an Angular project using the @agm package as we have already discussed here.

In this tutorial, we will focus on adding a Circle Radius in the map to limit the markers shown to the user. A user can control up to how far the markers/ locations should be visible.

This is a practical situation where we can’t show all the country’s location if a person wants to view the same city results.

For the basic installation of Google Maps, you can check my previous post here. In this post, we will only focus on adding a Radius circle with logic on How to show only those markers that reside in the Radius Circle.

Check the working demo here.

Adding Google Map

In the component template, we will add 4 component directives provided by the @agm package to create a map.

agm-map: Add a map on the component.
agm-marker: Component directive to show a marker on the map.
agm-info-window: Each marker can have an info window to show data on marker click.
agm-circle: Creates Circle for Radius on map.

 

Let’s place the below HTML template in the component

In the controller class import MapsAPILoader to get map load callback to call setCurrentLocation() method which will get current coordinates and fill the markers array with dummy 50 coordinates to test our Radius circle.

Also, add map height in CSS:

 

Show Markers on Map which lie in Radius Circle

On Radius Circle dragEnd event we call the showHideMarkers() method to loop over all markers and ser its isShown property based on a check in the getDistanceBetween() method if the marker’s coordinates lie in Radius we set on the map.

How to get the distance between two Coordinates on a map?

To get the distance in meters between two coordinates google service provides the computeDistanceBetween() method which takes two LatLong objects to calculates the distance between them as a straight line on earth’s surface.

Final component class code will look as shown below:

 

Leave a Reply

avatar
  Subscribe  
Notify of