Display the user's location on Google Maps in addition to all other markers for a comprehensive view

How can I modify the code to prompt the user for their location only when they click on a specific button, and then show all markers on the map? This jsfiddle illustrates the current issues: Google map loads markers from a database, and the user is asked by the browser if they want to share their position. Here are my questions:

  1. How do I make the browser ask for the user's position only when they click on the "Show my position" button? How can I implement this in the code so that if the button is not clicked, the map shows the other markers instead?
  2. When the user clicks on "Show my position," how can I adjust the map to fit all markers on the screen and make them visible?
<button>Show my position</button>
<div id="googlemap"></div>

You can view the jsfiddle here.

Note: JSFiddle may not work on Internet Explorer. Thank you for your assistance!

Answer №1

Make sure to assign an ID to your button, like this:

<button id="showPosition">Display my location</button>

Utilize the fitBounds() method to encompass the user's location on the map.

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
        var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        marker = new google.maps.InfoWindow({
            map: map,
            position: pos,
            zoom: 5,
            content: 'You are here !',

        });
        bounds.extend(marker.position);

        map.fitBounds(bounds); // adjust the map with the expanded bounds

    }, function () {
        handleNoGeolocation(true);
    });
} else {
    // Geolocation is not supported by the browser
    handleNoGeolocation(false);
}

Remember to enclose your code within a click event listener:

Traditional Method

document.getElementById("showPosition").addEventListener('click', function () {

    // insert code here
});

Google Maps Approach

google.maps.event.addDomListener(document.getElementById('showPosition'), 'click', function () {

    // insert code here
});

Answer №2

  1. For the browser to request user permission only when the 'Show my position' button is clicked, you can add an onclick event to the button and then check for the navigator.geolocation condition upon clicking.

Here's an example:

<button id="showMe">Show my position</button>  

Managing user permission :

document.getElementById("showMe").addEventListener('click', function () {
    if(navigator.geolocation) {
        // If the user grants permission
    } 
});

Now, the browser will only prompt for permission when the button is clicked.

  1. To adjust the map area to fit the new marker, utilize the bounds to incorporate the new marker and then adjust the map like so :

    bounds.extend(pos);
    map.fitBounds(bounds);
    

Therefore, your updated code will resemble this:

document.getElementById("showMe").addEventListener('click', function () {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
        var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

        marker = new google.maps.InfoWindow ({
            map: map,
            position: pos,
            zoom:5,
            content: 'You are here !'
        });

    bounds.extend(pos);      // adding the new marker to the bounds.
    map.fitBounds(bounds);   // adjusting the map to cover the bounds.

    }, function() {
           handleNoGeolocation(true);
       });
    } else {
        handleNoGeolocation(false);
    }
});

Here is an updated jsFiddle.

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

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...

Develop fresh JavaScript code using JavaScript

Is it possible to dynamically create a new row in an HTML table by clicking on a button? Each row contains multiple input fields. <script type="text/javascript> row = 2; specific_row_id = new Array(); $(document).ready(function() { $(".change_1 ...

Padding on hover for navigation bar dropdowns

Having issues with a drop-down navigation menu that works fine except for the "videos" item. The hover color change doesn't cover the entire width due to padding settings. Struggling to fix this without affecting the "photography" item. Need help figu ...

Scrolling a table to the current ng-init date in AngularJs: What’s the best approach?

I found a code snippet in my DOM that sets the current date on a table. <table id="daysTableLeft" class="table table-hover" ng-init="getHorraire(pickDateRow,$index,0)"> <tr ng-repeat="fd in getFullDayDate track by $index ...

AngularJS Alert: [$injector:unpr] Provider Not Recognized

After setting up the URL routes for the sportsStore app from an AngularJS book to learn, I'm encountering the following errors: Error: [$injector:unpr] Unknown provider: $templateRequestProvider <- $templateRequest <- $route <- ngViewDirect ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Transferring a Variable from Arduino to JavaScript

Is there a simple way to pass an Arduino variable as a JS variable? Let's say we have an integer Arduino variable called sensorData: int sensorData = analogRead(sensorPin); How can we transfer this value to a JavaScript variable? client.println(&quo ...

jQuery carousel displaying a blank slide at the conclusion

I am experiencing an issue with my slideshow where it shows an empty slide after the last element. I suspect that there is something in my script causing this behavior, as it seems to be finding one extra child for the element and adding it as an empty spa ...

Exploring the Depths of NodeJS X-Ray Web-Scraper: Uncovering Hidden Gems within Sub Pages

Currently, I am attempting to scrape content using the node.js x-ray scraping framework. While I have successfully retrieved data from a single page, I am struggling with navigating through links and extracting content from subpages simultaneously. Althou ...

I encountered an issue when sending a PATCH request via Hoppscotch where the request body content was returned as 'undefined', although the username and ID were successfully

const express = require("express"); const app = express(); const path = require("path"); let port = 8080; const { v4: uuidv4 } = require('uuid'); app.use(express.urlencoded({extended: true})); app.set("views engine", ...

What could be the reason for angularjs not functioning as expected?

After attempting to create a basic JavaScript unit test using angular.js, I encountered failure without understanding the reason behind it. test.html <html> <head> <script src="angular-1.2.21/angular-scenario.js" ng-autotest></ ...

How to Retrieve the Value of <input type=date> Using TypeScript

I am currently developing a survey website and need assistance with retrieving user input for two specific dates: the start date and end date. I aim to make the survey accessible only between these dates, disabling the "take survey" button after the end da ...

Determine whether the input fields contain specific text

I'm currently working on a script that checks if the user input in an email field contains specific text. It's almost there, but it only detects exact matches instead of partial matches. If the user enters anything before the text I'm trying ...

What is the best way to deactivate all 67 checkboxes once 4 of them have been chosen?

I am looking to limit the selection of checkboxes to only 4 out of a total of 67. However, I am currently struggling to figure out how to monitor the checkboxes and determine if exactly 4 have been selected. <table class="mdl-data-table mdl-js-data-t ...

Error encountered: Application module "MyApp" not found

I have set up AngularJs and jQuery using RequireJs within a nodeJs framework. This is my main.js setup require.config({ paths: { angular: 'vendor/angular.min', bootstrap: 'vendor/twitter/bootstrap', jqu ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

Error: Uncaught promise rejection - The function is undefined in the context of Vue.js and Electron

I've been experimenting with anime.js to animate elements using promise functions. However, I'm encountering an issue where the second function does not run after the previous one successfully completes. <script> import Splash from '. ...

What is the best way to integrate Bootstrap 5 with Next.js?

After adding Bootstrap to my project with npm install bootstrap, I included the style in /pages/_app.js like this: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Component, pageProps }) { return <Component {...pag ...

"Unlocking the Power of Social Interaction with Vue.js

I've successfully integrated a Facebook Login module in my project and it's working well. However, I'm facing difficulties when trying to link the response data with an input field. Can someone guide me on how to achieve this? I'm still ...