SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Objectives
  • Starter Code
  • Geocoding Addresses
  • Example:
  • Using Geocoder
  • Try this in a separate file
  • Geocoding with a database model
  • Using Google Maps
  • Getting an API key
  • Adding a map div
  • Link to Google Maps
  • Add a Map Script
  • Setting up markers
  • Useful links
  1. Node/Express
  2. Additional Topics

Geocoding and Google Maps

PreviousGeocoding with MapboxNextCloudinary

Last updated 3 years ago

Objectives

  • Describe the reversable process of geocoding.

  • Utilize geocoding with a geocoder and Sequelize hooks

  • Use Google Maps to add geocoordinates to a map.

Starter Code

We'll be using the starter code here (fork and clone):

Geocoding Addresses

What is geocoding? - The process of converting a description of a place to geographic coordinates. The relationship between the description and the place is a mapping (no pun intended).

Example:

"Seattle, WA" -> geocode -> {lat: 47.6062095, lng: -122.3320708}

Using Geocoder

First lets install the package into our starter code. Note that we'll be using Google's geocoder API.

npm install geocoder

Try this in a separate file

We'll use this code in a file called mapTest.js

var geocoder = require('geocoder');
geocoder.geocode('Seattle, WA', function(err, data) {
  console.log(data.results[0].geometry.location);
});

Note that once we type a location, the geocoder will lookup and give us coordinates for the location.

Geocoding with a database model

In the starter code, we have a model called place that has a name, address, lat (latitude), and lng (longitutde) attributes.

If we want to take an address a user typed in, then determine the coordinates for the address, we can generate the coordinates using the geocoder library and a Sequelize beforeCreate hook. Let's try that in place.js.

At the top of the place model, import the geocoder.

var geocoder = require('geocoder');

Then, add a hook below the classmethods object

hooks: {
  beforeCreate: function(place, options, cb) {
    geocoder.geocode(place.address, function(err, data) {
      if (err) return cb(err, null);
      place.lat = data.results[0].geometry.location.lat;
      place.lng = data.results[0].geometry.location.lng;
      cb(null, place);
    });
  }
}

Now, try starting the app and entering a name/address. The geocoder will take the address and attempt to find the geocoordinates for the address. Check in the database to see if these results are generated.

Using Google Maps

Google Maps is the most popular mapping app on the web. We'll be using it to display places on a map. In order to do so, we need geocoordinates of the places, which we already set up!

Getting an API key

Click on "Google Maps JavaScript API." Click "Enable." Use the API Manager pane on the left to navigate to "Credentials." Select "API Key" from the "Create credentials" drop down menu. Choose "Browser Key." Name the key something like "Google Maps Browser Key" and leave the referrers field blank. Now you have your browser key.

The two APIs you need to enable are the Google Maps JavaScript API, and the Google Maps Embed API. You might want to use the Google Maps Places API eventually, so go ahead and enable that too.

Adding a map div

We already set up a map div in the index.ejs template, along with some CSS to set up the height. Take a look in order to familarize yourself. The CSS is important because if the div has no height, the map won't display.

index.ejs*

<div id="map"></div>

style.css

#map {
  height: 500px;
}

Link to Google Maps

In order to use Google Maps, you need to link to the maps script, along with the API key. These API keys are special browser keys, which don't need to be private (and can't be private, since everything on the front end is visible).

Add a Map Script

Let's add the script in index.ejs before our custom script.

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

Note that there's a callback at the end of the script. This parameter defines the function that's called when the Maps API script is finished loading.

REMEMBER TO CHANGE OUT THE KEY PARAMETER WITH YOU API KEY BEFORE CONTINUING

Again, since the API key is front-end facing, and only really used for usage metrics, you don't need to be hide it. That said, it's good practice to include the key as an environment varaible, so that you can switch keys if they are expired or get reset.

Example:

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=<%= process.env.API_KEY_NAME %>&callback=initMap">
</script>

Now, let's define our initMap callback inside script.js. We'll be doing a series of operations inside this function.

  • Creating a map attached to map, including a center point and zoom level

  • If the browser supports geolocation, we'll ask the user their location and recenter the map if possible

  • Add markers to the map by iterating across the array of markers (currently empty, but we'll fill the array soon)

    • Also, we'll bind a popup to each marker, displaying the location's name

var initMap = function() {

  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 10
  });

  // if brower support available, ask user for location data and set the map view
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var initialLocation = new google.maps.LatLng(
        position.coords.latitude,
        position.coords.longitude
      );
      map.setCenter(initialLocation);
    });
  }

  // for each marker passed through, add it to the map with a popup
  markers.forEach(function(marker) {
    console.log(marker);
    var position = new google.maps.LatLng(marker.lat, marker.lng);
    var googleMarker = new google.maps.Marker({
      position: position,
      title: marker.name,
      map: map
    });
    // Bind a popup to the marker
    googleMarker.addListener('click', function() {
      var infoWindow = new google.maps.InfoWindow({
        content: '<h3>' + marker.name + '</h3>'
      });
      infoWindow.open(map, googleMarker);
    });
  });
};

IMPORTANT NOTES

  • It's important that you remember the async and defer attributes on the Google Maps script tag. This will wait until the page has loaded to start loading the Google Maps script.

  • initMap is distinct from the $(document).ready() event. According to this Stack Overflow post, deferred scripts will execute before jQuery's $(document).ready() function.

Setting up markers

Lastly, we need to get markers from our database and display them on the map. In order to do so, we'll add a script tag on the index.ejs template to show render points to the page. Note that it's very important to do this on a EJS template, otherwise, we can't use the EJS template tags.

In index.ejs before all the other scripts:

<script>
  var markers = <%- JSON.stringify(places) %>;
</script>
  • JSON.Stringify will convert our data to JSON data that javascript can use.

  • <%- %> syntax will display it exactly, and not escape it for html.

Useful links

You'll need a Google/Gmail account first before setting up the API key. Once you've got that, head to the . You'll see a bunch of links to various APIs, and the only ones you care about right now are the Maps APIs.

Here's an example of adding the map script. Alternatively, you can find a walkthrough for including the Google Map script tag . They also help out with automatically pasting your API key.

https://github.com/WDI-SEA/express-geocode-maps-example
Google developers console
here
http://stackoverflow.com/questions/8638551/script-defer-and-document-ready
Google maps API reference
Google developers console