JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  • Geolocation in Our Browser
  • Using Geolocation Information
  • LatLng
  • Options for Map
  1. 03-API Fundamentals
  2. 4-Apps
  3. 03-GoogleMaps

JS Setup

PreviousAPI KeyNextAdding Your Location

Last updated 7 years ago

Geolocation in Our Browser

Before we do anything with the GoogleMaps API, we have to setup the JavaScript file to pull location data from GoogleMaps. For the moment, this will only display a map of your location. How can we get the geolocation information from our user? There is a way we can do this! From the Mozilla docs: The Navigator.geolocation read-only property returns a Geolocation object that gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user's location. So the first thing we can do is utilize this!

We're going to be working in our googlemaps.js file. Start with the following code:

if("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function(position) {

    });
    } else {
    var para = document.createElement('p');
    para.textContent = 'Argh, no geolocation!';
    document.body.appendChild(para);
    }

Here, we are checking to see if the browser can find the geolocation information. We need a way to handle two situations: If the information exists, or if it doesn't. If there is for now, we're just starting by using getCurrentPosition() on that geolocation. From the docs: The Geolocation.getCurrentPosition() method is used to get the current position of the device. If there isn't geolocation, we obviously can't use geolocation in our app, so we're going to create a p tag on the html page and fill it with the error string. This way, the user can see that there is an error.

Using Geolocation Information

So, now, if we have our geolocation information, let's use it. We want to take the position that we got from getCurrentPosition() and use it. We need to figure out the best way to use this information with the GoogleMaps API to get a map to appear. From the docs , we notice that we need certain information to create a map. From the GoogleMaps API Docs: Map(mapDiv:Element, opts?:MapOptions) Creates a new map inside of the given HTML container, which is typically a DIV element. So we need to have an HTML container, which we've already created, and then we have the options parameter, which is optional.

If you check out the part in the docs for the options , you can see some of the options that we can provide to create our Map. Of particular importance is this one:

center    
Type:  LatLng
The initial Map center. Required.

This is a required option, we need to tell the API where to center the map. Notice that the type is LatLng. What is that??

LatLng

Okay, so now we know how we can create our LatLng, which we need to be able to create a map. Let's first do that in our JS file. We're going to take the geolocation information given to use from our browser as position. Then we're going to use that position information to get the latitude and the longitude to use in our LatLng constructor.

if("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function(position) {
    var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    });
} else {
    var para = document.createElement('p');
    para.textContent = 'Argh, no geolocation!';
    document.body.appendChild(para);
}

Options for Map

if("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function(position) {

    var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      disableDefaultUI: true,
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    });
} else {
    var para = document.createElement('p');
    para.textContent = 'Argh, no geolocation!';
    document.body.appendChild(para);
}

So, above, we used zoom, center, mapTypeId, disableDefaultUI. If you want more information on those, check out the docs linked above. Then we use our Map constructor to create a map on the HTML element with an id of map_canvas using the options we set up!

Open the HTML page in your browser and click yes when it prompts you to allow location services. You should see this:

If the app works, commit the code.

Take a look at Google's docs on . There's a lot of good information here. We have two questions we need to answer: What is LatLng, and how can we use it? Here is Google's definition of latlng: A LatLng is a point in geographical coordinates: latitude and longitude. So it's latitude and longitude, makes sense. How can we use this? They include this information under constructor: LatLng(lat:number, lng:number, noWrap?:boolean) Creates a LatLng object representing a geographic point. Latitude is specified in degrees within the range [-90, 90]. Longitude is specified in degrees within the range [-180, 180]. Set noWrap to true to enable values outside of this range. Note the ordering of latitude and longitude.

Awesome! Now we have our LatLng set up, we can look at other options. Look back at the to check out the possible options. We'll use some of them to create our map below. If you want to, feel free to play with different options to see what they do/how they work. We'll use the following code.

here
here
LatLng
docs
Basic App