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:

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

Incorporating Javascript into a <script> tag within PHP - a step-by-step guide

I am trying to integrate the following code into a PHP file: if (contains($current_url, $bad_urls_2)) { echo '<script> $('body :not(script,sup)').contents().filter(function() { return this.nodeType === 3; ...

What is the best way to preload all videos on my website and across different pages?

I specialize in creating video websites using HTML5 with the <video> tag. On my personal computer, the website transitions (fadeIn and fadeOut) smoothly. However, on my server, each page seems to take too long to load because the videos start preloa ...

What is the best way to ensure that a task is performed only once the DOM has finished loading following an AJAX request

<div id="mydiv"> ... <a id="my-ajax-link"> ... </a> ... ... <select id="my-selectmenu"> ... </select> ... </div> Upon clicking the 'my-ajax-link' link, it triggers an AJ ...

Updating the database with values dynamically using ajax without the need to refresh or change the current page

My current challenge involves adding records to a database table without the need to reload the page. I've implemented ajax for this purpose, but have been receiving an unexpected response (201) from the server (alert("Error occurred !")). Despite spe ...

What is the best way to initially hide a div using slide toggle and then reveal it upon clicking?

Is there a way to initially hide the div tag and then animate it in a slide toggle effect? I attempted using display:none on my '.accordion_box' followed by show() in slideToggle, but this results in adding the CSS property display: block. My goa ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

What is the best method for circumventing an express middleware?

I am currently working on an express application that utilizes several express routes, such as server.get('*' , ... ) to handle common operations like authentication, validation, and more. These routes also add extra information to the respon ...

How to retrieve the present value from an array using AngularJS

Struggling to assign the current user from my list Here is my array after submitting the form [{"name":"Erich","surname":"Josh","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096c67497a7a276a6664">[email prot ...

Utilizing icons with vuetify's v-select component: a guide

In the code snippet below, I am using a v-select element to display a list of items filled from an array: <v-select v-model="myModel" :items="users" chips :readonly="!item.Active" label="Required users to f ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed. The AJAX call executes successfully a ...

Importing ES module into Next.js leads to ERR_REQUIRE_ESM

Encountered this issue while attempting to integrate ky into a Next.js project: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js It seems that the cause of this problem is Webpack (or Babel) converting all import ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

My messages are falling on deaf ears as the Discord bot remains unresponsive (js)

After creating a Discord bot using node.js and VS Code, I am encountering an issue where the bot appears online but does not respond to messages. Despite ensuring that the bot has all the necessary permissions, I cannot identify the root cause of this prob ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...

What is the best way to align a popup window with the top of the main window?

I have successfully created a simple lightbox feature where a popup window appears when a thumbnail is clicked. My question is, how can I use jQuery to detect the top position so that the popup div always appears around 200px from the top of the window? $ ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...