Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8726369
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T08:13:52+00:00 2026-06-13T08:13:52+00:00

I have the following code to detect the visitors GPS position and show it

  • 0

I have the following code to detect the visitors GPS position and show it on the Google Maps JavaScript v3 map. Everything works as I want it but the code will not center or zoom as I want – it simple use the standard position (right over Asia)! I want it to fit the markers on the map.

var rendererOptions = {
    draggable: false
};

if(navigator.geolocation) {
    var timeoutVal = 10 * 1000 * 1000;

    navigator.geolocation.watchPosition(
        displayPosition,
        displayError,
        { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
    );
} else {
    alert('Din webbläsare stödjer inte någon geologisk lokalisering med hjälp av HTML5');
}

var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var marker_gps;
var map_gps;
var options_gps;





function displayPosition(position) {


    /***********************
    **    GPS-POSITION    **
    ************************/

    directionsDisplay = new google.maps.DirectionsRenderer();
    localStorage.coor = position.coords.latitude.toFixed(6) + ',' + position.coords.longitude.toFixed(6);

    var gps_coor = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));

    if(typeof(marker) != 'undefined') marker.setMap(null);

    localStorage.accuracy = position.coords.accuracy;
    document.getElementById('accuracy').innerHTML = number_format(localStorage.accuracy) + ' meter';

    directionsDisplay.setMap(map_gps);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));

    marker_gps = new google.maps.Marker({
        position: gps_coor,
        draggable: false,
        map: map_gps
    });

    var circle_gps = new google.maps.Circle({
        center: gps_coor,
        radius: position.coords.accuracy,
        map: map_gps,
        fillColor: '#3333ff',
        fillOpacity: 0.2,
        strokeColor: '#3333ff',
        strokeOpacity: 0.5,
        strokeWeight: 1
    });



    /*****************************
    **    FÄRDSÄTT (DISTANS)    **
    ******************************/

    var start = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));
    var stop = new google.maps.LatLng(<?php echo $photo['coordinates_latitude'].','.$photo['coordinates_longitude']; ?>);

    var request = {
        origin: start,
        destination: stop,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if(status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });

    directionsService.route(request, function(response, status) {
        if(status == google.maps.DirectionsStatus.OK) {
            var distance = (response.routes[0].legs[0].distance.value / 1000).toFixed(0);
            var duration = secondsToString(response.routes[0].legs[0].duration.value);

            document.getElementById('distance').innerHTML = 'Cirka ' + distance + ' kilometer';
            document.getElementById('duration').innerHTML = 'Cirka ' + duration;

            directionsDisplay.setDirections(response);
        }
    });


}



function initialize_gps() {
    var coor = new google.maps.LatLng(localStorage.coor);
    var bounds = new google.maps.LatLngBounds();

    options_gps = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: google.maps.LatLng(localStorage.coor),
        streetViewControl: false
    }

    map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
    map_gps.fitBounds(bounds);
}







function secondsToString(seconds) {
    var numdays = Math.floor(seconds / 86400);
    var numhours = Math.floor((seconds % 86400) / 3600);
    var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);

    return (numdays != 0 ? (numdays == 1 ? '1 dag' : numdays + ' dagar') + ', ' : '')
         + (numhours != 0 ? (numhours == 1 ? '1 timme' : numhours + ' timmar') + (numdays != 0 ? ', ' : ' och ') : '')
         + (numminutes != 0 ? (numminutes == 1 ? '1 minut' : numminutes + ' minuter') : '');
}

function displayError(error) {
    var errors = {
        1: 'Permission denied',
        2: 'Position unavailable',
        3: 'Request timeout'
    };

    alert('Error: ' + errors[error.code]);
}

How can I make this to work?

Thanks in advance.

EDIT

Here’s the edited part of the initialize_gps function. This part didn’t work – nothing new happened. It just center the map over Asia like before.

function initialize_gps() {
    var coor = new google.maps.LatLng(localStorage.coor);
    var bounds = new google.maps.LatLngBounds();

    options_gps = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: google.maps.LatLng(localStorage.coor),
        streetViewControl: false
    }

    map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
    map_gps.fitBounds(bounds);
}

EDIT

I have copy-pasted the whole code to jsFiddle. Link: http://jsfiddle.net/edgren/WRxt4/

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T08:13:53+00:00Added an answer on June 13, 2026 at 8:13 am

    The general solution to fitting the map display to a set of markers is to add them to an empty google.maps.LatLngBounds object (by calling bounds.extend), then calling map.fitBounds with that bounds.

    function setMarkers(map) {
      var bounds = new google.maps.LatLngBounds();
      // Adds markers to the map.
      for (let i = 0; i < beaches.length; i++) {
        const beach = beaches[i];
        var marker = new google.maps.Marker({
          position: { lat: beach[1], lng: beach[2] },
          map,
          title: beach[0],
        });
        bounds.extend(marker.getPosition());
      }
      map.fitBounds(bounds);
    }
    
    // The following example creates complex markers to indicate beaches near
    // Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
    // to the base of the flagpole.
    function initMap() {
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 10,
        center: { lat: 0, lng: 0 },
      });
      setMarkers(map);
    }
    // Data for the markers consisting of a name, a LatLng and a zIndex for the
    // order in which these markers should display on top of each other.
    const beaches = [
      ["Bondi Beach", -33.890542, 151.274856, 4],
      ["Coogee Beach", -33.923036, 151.259052, 5],
      ["Cronulla Beach", -34.028249, 151.157507, 3],
      ["Manly Beach", -33.80010128657071, 151.28747820854187, 2],
      ["Maroubra Beach", -33.950198, 151.259302, 1],
    ];
    
    function setMarkers(map) {
      var bounds = new google.maps.LatLngBounds();
      // Adds markers to the map.
      for (let i = 0; i < beaches.length; i++) {
        const beach = beaches[i];
        var marker = new google.maps.Marker({
          position: { lat: beach[1], lng: beach[2] },
          map,
          title: beach[0],
        });
        bounds.extend(marker.getPosition());
      }
      map.fitBounds(bounds);
    }
    /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
    #map {
      height: 100%;
    }
    
    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Complex Marker Icons</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <!-- jsFiddle will insert css and js -->
      </head>
      <body>
        <div id="map"></div>
    
        <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
        <script
          src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"
          async
        ></script>
      </body>
    </html>
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code and I want to detect in which port client
I have the following code I want to detect the screen off of the
I have the following code and I want to detect the circle. img =
I have following code. ASPX Page <a href=AnyASPXPageOfWebsite.aspx onclick=javascript:CallJQuery(); > Set Price </a> JS
I have the following code that I want to use to search a database
I have the following php code to detect and replace links: //Detect links $pattern_url='~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*<>|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';
I have the following code to detect user navigation or close. The post back
I have the following code (implemented in the mouseReleaseEvent) to detect when the user
I have the following code (as i am trying to detect changes to a
I have the following PHP code: $required_fields = array ('menu_name','visible','position'); foreach($required_fields as $fieldname) {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.