Displaying markers and coordinates in the center circle of a Google Map using Vue.js

Is there a way to display the markers that fall within the specified radius on my map? I need to showcase these locations based on their proximity to a central point, as this will be essential for developing a function that identifies places within a certain kilometer radius.

Take a look at my map: https://i.sstatic.net/sGUOo.png

You'll notice that I have numerous markers on the map, fetched from my database using an Axios request.

Below is a snippet of my code:

data() {
    return {
        clinics: [],
        points: '',
        property: {
            lat: 1.28237,
            lng: 103.783098
        },
        diameter: 5000
    }
},
methods: {
    initMap() {
        // Center marker within circle
        const map = new google.maps.Map(document.getElementById('map'), {
            zoom: 13,
            center: this.property
        })
        const circle = new google.maps.Circle({
            map: map,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            radius: this.diameter,
            center: this.property
        });
        const marker = new google.maps.Marker({
            position: this.property,
            map: map
        });

        // Other Markers
        for (var i = 0; i < this.clinics.data.length; i++) {
            var coords = this.clinics.data[i].coord;
            var details = this.clinics.data[i].clinic;
            var latLng = new google.maps.LatLng(coords['lat'], coords['lng']);
            var markers = new google.maps.Marker({
                position: latLng,
                map: map,
            });
            const contentString = '<div id="content"><p>' + details + '</p></div>';
            // Info window functionality
            this.infoWindowShow(markers, contentString);
        }
    }
}

Answer №1

To determine if a marker should be plotted inside a circle on the map, you can create a function within your for loop that calculates the distance between the center of the circle and the marker's coordinates. If this distance is less than or equal to the radius specified, then the marker should be shown. Your code should resemble the following:

    for (var i = 0; i < this.clinics.data.length; i++) {
               var coords = this.clinics.data[i].coord;
               var details = this.clinics.data[i].clinic;
               var latLng = new google.maps.LatLng(coords['lat'], coords['lng']);

        //Get distance between the center of the circle and the coordinates
    var dist  = google.maps.geometry.spherical.computeDistanceBetween(CenterOfCircle, latLng);    

    //If distance is less than the radius, plot the markers in the map
    if (dist <= radiusOfCircle){
               var markers = new google.maps.Marker({
                  position: latLng,
                  map: map,
               });
               const contentString = '<div id="content"><p>' + details + '</p></div>';
               //for Info window function
               this.infoWindowShow(markers, contentString);
            }
  }

You can utilize the computeDistanceBetween() method from the Geometry library. Ensure that 'libraries=geometry' is included in the script loading the Google Maps API.

For a basic implementation example, check out a simple looping through coordinates code snippet here, and a modified version focusing on plotting markers only within the circle.

Hopefully, this solution aligns well with your project needs!

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

Learn the steps for assigning a distribution tag to an npm package within a private registry

Operating with my own exclusive Gemfury repository, I am actively releasing npm packages. Intrigued by the prospect of applying distribution tags to my packages (as per this guide: https://docs.npmjs.com/cli/dist-tag). The configuration of my npm registr ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

The useReducer function dispatch is being called twice

I can't figure out the reason behind this issue. It seems that when strict mode is enabled in React, the deleteItem function is being executed twice. This results in the deletion of two items instead of just one - one on the first round and another on ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it au ...

Receiving a JSON object in response after sending data to a server using JavaScript

I am facing an issue with passing an email and password on login click to a database using PHP. After testing the email and password combination, PHP sends back a JSON object. While I have verified that the PHP code is functioning correctly and returns a J ...

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...

What is the process for sending a POST request from a React app to a Node.js Express server?

I watched a tutorial video on resolving the CORS issue, which worked well for GET requests. However, I encountered an issue when attempting to send a POST request. Unfortunately, I do not have control over the third-party API and cannot make any changes to ...

Using Node.js to create a RESTful API that pulls information from MongoDB

I am currently working on creating a REST API using Node.js to retrieve the last N rows from a MongoDB collection. Here is my current code snippet: var express = require("express"); var app = express(); var bodyParser = require("body-pa ...

Choose one of the options provided by the radio button that best fits the question using Playwright

Can Playwright docs be used to select a radio button answer based on the question and answer? I need to answer a series of yes/no questions. Here's the HTML structure of the survey site: <!DOCTYPE html> <html lang="en"> <bod ...

How can aframe be integrated and utilized in Vue applications?

Trying to integrate aframe with vue-cli has been a challenge for me. I've experimented with adding aframe directly in the index.html file, as well as importing it in my top level main.js file, but I haven't had any success in getting Vue to recog ...

The overflow hidden property does not seem to be effective when used in conjunction with parallax

The issue arises when I attempt to use the overflow hidden property in combination with parallax scrolling. Although everything seems to be working correctly with JavaScript for parallax scrolling, setting the overflow to hidden does not contain the image ...

Is there an issue with JQM plugin due to jQuery's append() function?

I am just starting to learn about jQuery mobile as I develop an app using it. Whenever I click on the Add_details button, I want to add dynamic input fields only once. After saving, if I click on the Add_details button again, I need to append more dynamic ...

Adjust webpage display with JavaScript

Utilizing the mobile-first approach of Zurb Foundation, I successfully created a responsive design. However, my client now requires a direct link labeled "View desktop version" in the footer for when the website is accessed on mobile devices or tablets. T ...

Sluggish Bootstrap Carousel Requires Mouseover or Click to Start Sliding

Having Trouble with Bootstrap Carousel Sliding: I've been trying to solve this issue for a while now, but nothing seems to be working. I know this might be a common question, but I really need to fix this problem quickly and none of the suggested solu ...

Is it possible to combine multiple filter examples together?

Could you please provide some examples or references related to the next task: var planets = [{ residents: [{ name: 'Mars' }, { name: 'Jupiter' }, ...

I'm trying to use Route.get() but it seems I forgot to include a callback function. What mistake did I make?

I've searched through various answers on different platforms, but I'm still struggling to understand. What mistake have I made? Can someone provide assistance? *revised. I have included requiring routes and app.use. It seems like the function is ...

In AngularJs, use ng repeat and ng switch to dynamically generate and display tables

I need help rendering a table with two columns using angularjs directives. <table> <tr ng-repeat="message in messages" > <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController"> <span> ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Combining ExtJS Paging with Dropdown Selection

Having an issue with a combo box created using the ExtJS framework. The pagination feature is not working correctly. Can anyone provide assistance with this? var store = new Ext.data.ArrayStore({ fields: ['id'], pageSize:1, data : ...