Attempting to retrieve a custom Google map with a specified user-defined radius

I'm currently working on implementing a feature that allows users to set the radius from their center location on a Google map. While I have most of the code in place, I'm struggling to get it fully functional. Below is the snippet of code I've been using. Any assistance would be greatly appreciated.

CSS and HTML Code

Search Radius:
    <input type="range" name="search_radius" id="search_radius" min="10" max="100">
    <script>
        // Add a Circle overlay to the map.
        circle = new google.maps.Circle({
            map: map,
            radius: 10
        });

        // Binding the Circle's center to the Marker's position.
        circle.bindTo('center', marker, 'position');

        $("#search_radius").slider({
            orientation: "vertical",
            range: "min",
            max: 3000,
            min: 100,
            value: 500,
            slide: function(event, ui) {
                updateRadius(circle, ui.value);
            }
        });

        function updateRadius(circle, rad) {
            circle.setRadius(rad);
        }

        google.maps.event.addDomListener(window, 'load', init);

    </script

<center>
    <script>getLocation();</script>
    <button onclick="getLocation()">Get My Location</button><p id="map"></p>

    Search Radius:
    <input type="range" name="search_radius" id="search_radius" min="10" max="100">
    <script>
        // Adding a Circle overlay to the map.
        circle = new google.maps.Circle({
            map: map,
            radius: 10
        });

        // Binding the Circle's center to the Marker's position.
        circle.bindTo('center', marker, 'position');

        // Setting up the slider for search radius adjustment.
        $("#search_radius").slider({
            orientation: "vertical",
            range: "min",
            max: 3000,
            min: 100,
            value: 500,
            slide: function(event, ui) {
                updateRadius(circle, ui.value);
            }
        });

        function updateRadius(circle, rad) {
            circle.setRadius(rad);
        }

        google.maps.event.addDomListener(window, 'load', init);

    </script

<!-- Checking Geolocation Support -->
<script>
var x = document.getElementById("map");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation not supported by this browser.";
    }
}

function showPosition(position) {
    var mapDiv = document.getElementById('map');
    var map = new google.maps.Map(mapDiv, {
      center: {lat: position.coords.latitude, lng: position.coords.longitude},
      zoom: 12
    });
}

function initMap() {
    var mapDiv = document.getElementById('map');
    var map = new google.maps.Map(mapDiv, {
      center: {lat: 53.3498, lng: -6.2603},
      zoom: 6
    });
}

</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>

Answer №1

Make sure to update the map's display after changing the radius of the circle. It is important to test the code provided below before implementing it.

function adjustCircleRadius(circle, newRad) {
  circle.setRadius(newRad);
  map.fitBounds(circle.getBounds());
}

For more information on map.fitBounds, refer to the documentation here.

It is advisable to have a single map object accessible by all functions and modify its center and zoom options instead of creating multiple map objects with different settings. Additionally, ensure that the map object is reachable by the initial script adding the circle in the current code.

var element = document.getElementById("map");
var map = new google.maps.Map(element, {
  center: {lat: 53.3498, lng: -6.2603},
  zoom: 6
});

function displayLocation(position) {
  element.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;

  map.center = {lat: position.coords.latitude, lng: position.coords.longitude};
  map.zoom = 12;
}

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

AngularJS - Setting an initial delay for ng-bind

We have a span element with the following attributes: <span role="link" ng-show="showLink()" ng-bind="textLink"></span> (Just an fyi: we implemented a fade-in, fade-out animation for this link, hence the use of ng-show instead of ng-if) The ...

Combine the promises from multiple Promise.all calls by chaining them together using the array returned from

I've embarked on creating my very own blogging platform using node. The code I currently have in place performs the following tasks: It scans through various folders to read `.md` files, where each folder corresponds to a top-level category. The dat ...

Invoking an AJAX function that is not inside the document.ready function

I'm having trouble populating a Google Map and here's some of the code I'm using. The ajax request doesn't seem to be working properly. When I put everything inside document.ready() as an anonymous function, it works fine. However, sinc ...

How can we automatically delete a message in DiscordJS after a certain amount of time has passed?

I am inquiring about DiscordJS and have a specific question. My query is regarding how to correctly remove a message sent by the bot on Discord. Admittedly, I am new to DiscordJS so please bear with me if this is a basic question. I appreciate all respo ...

How can I show a dynamic popover with specific content when a "Copy" action is triggered?

I am attempting to copy a value to the clipboard: /** * If the browser does not support direct clipboard manipulation, use an alternate method * This is used in the copyTextToClipboard function. * * Function found at: https://stackoverflow.com/a/3 ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

Sending information from popup to primary controller wit the use of AngularJS - (Plunker example provided) with an autocomplete field embedded in the popup

My scenario is a bit unique compared to passing regular data from a modal to the main controller. The input field in my modal has an autocomplete feature. Here is the Plunker I have included for reference: http://plnkr.co/edit/lpcg6pPSbspjkjmpaX1q?p=prev ...

Setting the file type when uploading content: a step-by-step guide

When uploading a file to an S3 bucket, it's essential to identify the file extension and add the correct content type. $('#upload-files').on('click', function(e) { e.preventDefault(); var fileName = data.files[0].name; var ...

Displaying dropdown options based on the previous selection made by the user

Can I link the data in my second dropdown to the selection made in the first dropdown? I tried a similar solution from stackoverflow without success. You can find the reference here. The code works when directly copied and pasted but not within my system. ...

It is imperative that the HTML div element remains within the boundaries of the page

Let me begin by providing some context. I am currently developing a responsive page that uses percentages to position my divs, allowing users to drag and drop items wherever they please. However, a problem arises when the user positions an object too close ...

SDK for generating templates with JavaScript/jQuery

I am in the process of developing an SDK in JavaScript/jQuery that can generate templates based on user input, such as profile templates and dialog templates. These templates require data from an AJAX call to be created. User input should include certain ...

Guide for executing Gulp tasks in a sequence one by one

Here is an example snippet: gulp.task "coffee", -> gulp.src("src/server/**/*.coffee") .pipe(coffee {bare: true}).on("error",gutil.log) .pipe(gulp.dest "bin") gulp.task "clean",-> gulp.src("bin", {read:false}) .pipe c ...

Conundrum regarding setting up configuration for express-session middleware in Express version 4.x

Hello, I'm currently diving into node.js and still trying to grasp the concept of configurations in sessions. Below is a basic example of how sessions are used in my app: app.js var express = require('express'); var bodyParser = require(&a ...

adding a new div to the bottom of a row that is being created on the fly

I encountered an issue where rows are created dynamically and I needed to add a div at the end of each row. Despite trying various methods, I faced difficulties as adding the div resulted in extra divs being added to all previous rows whenever a new row wa ...

Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it. I would like to change the positioning of these images to ...

JavaScript and AJAX are showing an error message that says: "ReferenceError: x is not

I am currently working on a jQuery function that retrieves the value from a PHP-generated checkbox and sends it through AJAX. The value being sent is always a single word consisting only of letters. Here is the script I have written: <script type="text ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

Duplicate the array of objects and make alterations without affecting the original array

I have an array of objects that I need to deep copy and make modifications to each object without altering the original array or its contents. Here is my approach in JavaScript, but I am open to suggestions on a better method. const users = [ { ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

Step-by-Step Guide on Uploading a File with a Basic jQuery-AJAX Request

I'm in need of a straightforward client-side script for ajax file uploading. I searched the web for such a script, but all I found were plugins with numerous features. I just want a simple ajax file upload script. Is it possible to create something l ...