Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I properly integrate the current location on top of a KML layer map?

function initialize() {
    var chicago = new google.maps.LatLng(49.051078,-122.314221);
    var mapOptions = {
        zoom: 11,
        center: chicago
    }

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

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

            var infowindow = new google.maps.InfoWindow({
                map: map,
                position: pos,
                content: 'Location found using HTML5.'
            });

            map.setCenter(pos);
        }, function() {
            handleNoGeolocation(true);
        });
    } else {
        handleNoGeolocation(false);
    }
}

function handleNoGeolocation(errorFlag) {
    var content;
    if (errorFlag) {
        content = 'Error: The Geolocation service failed.';
    } else {
        content = 'Error: Your browser doesn\'t support geolocation.';
    }

    var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
    };

    var infowindow = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}

var ctaLayer = new google.maps.KmlLayer({
    url: 'https://dl.dropboxusercontent.com/u/143598220/38EndsleighCrescent.kml'
});

ctaLayer.setMap(map);
}

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

Answer №1

This solution worked perfectly for me as it addressed the javascript errors, declared the map globally, and utilized preserveViewport on the KmlLayer to maintain the map's position without centering on the layer.

// Global variable declaration for the map
var map;
function initialize() {
  var chicago = new google.maps.LatLng(49.051078,-122.314221);
  var mapOptions = {
    zoom: 11,
    center: chicago
  }

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var ctaLayer = new google.maps.KmlLayer({
    url: 'https://dl.dropboxusercontent.com/u/143598220/38EndsleighCrescent.kml',
    preserveViewport: true

  });
  ctaLayer.setMap(map);

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

      var infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'Location found using HTML5.'
      });

      map.setCenter(pos);
    }, function() {
      handleNoGeolocation(true);
    });
  } else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
  }
}

function handleNoGeolocation(errorFlag) {
  var content;
  if (errorFlag) {
    content = 'Error: The Geolocation service failed.';
  } else {
    content = 'Error: Your browser doesn\'t support geolocation.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}


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

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

Can you explain the distinction between utilizing Object.create(BaseObject) and incorporating util.inherits(MyObject, BaseObject)?

Can you explain the difference between these two methods of setting the prototype? MyObject.prototype = Object.create(EventEmitter.prototype); MyObject.prototype = util.inherits(MyObject, EventEmitter); UPDATE I've noticed in various projects that ...

Using AJAX to send both data input values and file attachments simultaneously to a PHP server

I am currently having an issue with sending form values to my PHP page using AJAX. My form includes text inputs and a file input for image uploads. Below are the AJAX codes I have been working on: function sendval() { var form = $('#user_update_for ...

Vuetify: How to restore the input value in v-text-field

This app is designed with a simple v-text-field for user input. The issue I am facing is that when I enter a combination of numbers and letters like 11a, then quickly tab out or click out of the input field before losing focus, it only shows 11. However, ...

`Express.js Controllers: The Key to Context Binding`

I'm currently working on a project in Express.js that involves a UserController class with methods like getAllUsers and findUserById. When using these methods in my User router, I have to bind each method when creating an instance of the UserControlle ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

Troubleshooting issues with the controller functionality in AngularJS

The following code is not producing the expected output of 'Hello, World' output: {{ greetings.text }}, world Could someone please assist me in determining why it is not displaying 'hello, world' as intended <!doctype html> ...

How can the @blur event be added to the vue-bootstrap-typeahead in Nuxt/Vue application?

I am facing an issue where I want to trigger a function upon leaving an input field. The input in question is set up using vue-bootstrap-typeahead. Upon inspecting the DOM, I found that the structure of the input element looks like this: <div id="m ...

Insert JavaScript code into the head of the document (including the complete script code)

I am looking to insert a script in the head section of a website so that the target HTML appears as follows: <head><script type="text/javascript">*some code...*</script></head>. This particular script works perfectly: var head = d ...

Is it possible to have a never-ending slideshow with inline-blocks?

After spending countless hours trying to troubleshoot my code, I am now seeking help from the wonderful people of the internet! ;) It seems like only a small portion of my code is incorrect. What I'm attempting to do is move the leftmost object in the ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

Could anyone help me locate the section in the MUI documentation that explains the correct syntax for the commented code lines I am working on?

Before proceeding, please note that the ThemeProvider with theme={theme} has already been provided. Now, I will share two distinct sets of code files. These files contain sections commented out because they are not functioning as intended when implementing ...

Tips on Selecting a Typed Value

When clicking on 'no_results_text' and it's not available in the list, I want to show the searched value from the alert. I have included an onclick method for 'no_results_text', so that the typed value is displayed in the alert. h ...

Jquery cascading menu

I'm currently experiencing difficulties in creating dropdown menus using jquery and css. Below is my HTML code: <nav class="topNav"> <ul> <li> <a href="#menu" class="menu-toggle"><img src ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

The AngularJs 2 framework encountered an issue with booting up after attempting to combine all TypeScript files into a single JavaScript file

I am currently utilizing Angular 2 with TypeScript (V-1.8) in my project setup. I have configured my tsconfig to output the code into a single .js file. This single.js file includes the necessary code to bootstrap the application, as the boot.ts file is al ...

Is passportjs responsible for managing user registration?

Is it possible to utilize Passport for user signup if I am storing user information on a self-hosted server and cannot find a user signup function in the Passport.js documentation? ...

``To ensure Google Maps fills the entire height of its parent div, set the

Is there a way to display a Google Map at 100% of the parent div's height? I've noticed that setting the height to 100% makes the map not visible, but if I use a pixel value for the height, the map displays correctly. Are there any tricks or solu ...

Accessing a resource file from a compiled JAR archive

One issue that I am facing involves the project structure of my Maven Java project. It follows a typical layout: src/main/java - project .java files src/main/resources - project resources (log4j2.xml) src/test/java - .java files for tests src/test/r ...