An-dy1 / google-maps-api

Practicing using the Google Maps API to build a simple web app that displays the best places to long board in Kansas City.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Next level goals

- Improve styling - Automatically close info windows on next click - Store data for markers in a json file - Give users the ability to add a location on the map with info window - Before publishing a new card, require checking - Improve button styling - Figure out weird console error on MarkerClusterer - Bike routes don't show up on Satellite mode - Make menu/page responsive - Add an animation? Why not! - Refactor for React - Figure out moon positioning - Figure out necessity of global variables in script - Separate styles into individaul page files?

Snapshots

18 April - morning

first-18 second-18

11 April - afternoon

first second

My notes on using the Google Maps JS API

To add data to maps, there are two options:

  1. Overlays

    • Create the data ourselves programmatically, possibly in response to user input Examples:
    • Markers *
    • Polylines
    • Polygons
    • Circles
    • InfoWindows *
    • Ground overlays
    • Custom overlays
  2. Layers

    • Bring in data from somewhere else Examples:
    • KML Layers
    • Weather/Cloud
    • Heatmap
    • Traffic
    • Transit
    • Bicycle

Instantiating important stuff:

Make a map:

function initialize() {
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 11
  });

  var latLong = new google.maps.LatLng(39.0997, -94.5786);
  map.setCenter(latLong);

  changeTerrain(map);

Make a marker:

var centerMarker = new.google.maps.Marker({
    icon: [optional imageURL],
    position: new google.maps.LatLng([LAT, LONG]),
    map: map,
    title: "[TITLE HERE]"
});

Make a polyline (polygon is very similar):

var pathCoordinates = [
    new google.maps.LatLng(0, 0),
    new googlemaps.LatLng(0, 1),
];
var pathToCenter = new google.maps.Polyline({
    path: pathCoordinates,
    geodesic: false;
    strokeColor: '#fff',
    strokeOpacity: 1.0,
    strokeWeight: 2
});
pathToCenter.setMap(map);

Make an editable polygon:

function drawEditablePolygon(map) {
    var natureCoords = [
        new google.maps.LatLng(0, 1),
        new google.maps.LatLng(0, 2),
        new google.maps.LatLng(0, 3),
        new google.maps.LatLng(0, 4),
    ];

    var natureArea = new google.maps.Polygon({
        path: natureCoords,
        strokeColor: "#FFFFFF",
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: "#00FF00",
        fillOpacity: 0.6,
        editable: true
    });

    natureArea.setMap(map);
}

Draw a circle

function drawCircle(map) {
    var circle = new google.maps.Circle({
        map: map,
        center: new google.maps.LatLng (0, 0),
        fillColor: "#92D050",
        fillOpacity: 0.7,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 3
    });
    circle.setRadius(25);
}

Draw a draggable rectangle

function drawDraggableRectangle(map) {
    var bounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(52.340308, -3,052557),
        new google.maps.LatLng(52.340799, -3.050647)
    );
    var rectangle = new google.maps.Rectangle({
        bounds: bounds,
        map: map,
        fillColor: "#00FF00",
        fillOpacity: 0.6,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        draggable: true
    });
}

Make a ground overlay

Note: the two bounds refer to the southwest and northeast corners of a rectangular overlay.

Note: custom overlays are also an option, but require some elbow grease.

function drawGroundOverlay(map) {
    var imageBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(39.1097, -94.5786),
        new google.maps.LatLng(39.179877, -94.509405),
    );

    var groundOverlay = new google.maps.GroundOverlay(
        '/images/[PATH]', imageBounds
    );
    groundOverlay.setMap(map);
};

KML Layers and GeoRSS

  • Layers represent collections of objects with a common association
  • They are manipulated as a single unit

What is KML?

  • Keyhole Markup Language
  • Used to encode and display geographic data
  • Terrain and elevation data
  • Historical imagery
  • Based on XML standard
  • Must use google.maps.KmlLayer class
  • KmlLayerOptions includes map control, preserveViewPort option, and suppressInfoWindows
  • KmlLayerMetaData includes name, description, author, etc.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
    <Placemark>
    <name>Longboard Locale</name>
    <description>This is where we longboard</description>
        <Point>
            <coordinates>
                -50, 52, 0
            </coordinates>
        </Point>
    </Placemark>
</kml>

More examples:

  • Google Earth gallery
  • US Census data
  • Global Administrative Areas
  • "filetype:kml 'Lord of the Rings'"

What is GeoRSS?

  • Emerging (?) standard for encoding location as part of a web feed
  • Google maps can read GeoRSS feeds and use KML data to layer it on the map
function addKmlLayer(map) {
    var katyTrailLayer = new google.maps.KmlLayer('http://veloroutes.org/r/40124/kml');
    katyTrailLayer.setMap(map);
}

Adding GeoJSON data

function addGeoJSONDataLayer(map) {
    map.data.loadGeoJson('/add/path/here.json');
    map.data.setStyle({
        icon: '/set/path/here.pgn',
        strokeColor: 'aliceblue'
    })
}

Event Handling

The Google Maps JS API-approved way to add an event listener:

google.maps.event.addListener(
    marker,
    "click",
    function(){
        alert("Done clicked it now");
    }
);

Code that doesn't work to add a right click event listener to the map and set the map back to original bounds

function addGoToInitialExtent(map, latLong, initialZoom) {
  google.maps.event.addListener(map, 'click', function(){
    map.setCenter(latLong);
    map.setZoom(initialZoom);
  });
}

Resources

An inexhaustive list I only started halfway through the project of resources I've found helpful.

  • CSS Tricks article on switching text on a button click event (I used this on my "Show Bike Routes" button).

Using services to extend functionality

The Geocoding API

  • Geocoding is the process of translating an address to a set of coordinates, or vice versa
  • See new.html page and main.js

The Directions Service

A callback is a function passed as a parameter to the call to a service. It gets executed by the service when it completes its task. The service passes the results back as parameters to the callback function.

The HTML needed(in the same div as the map span):

<div>
    <input id="start" type="textbox" value="" style="width:300px;" />
    <input type="button" value="Get Route" onclick="calcRoute()" />
</div>
<div id="directionsPanel" style="float:right;width:30%;height:100%"></div>

The javascript needed:


function calcRoute() {
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay;
  directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directionsPanel'));

  var start = document.getElementById('start').value;
  var end = new google.maps.LatLng(39.148627, -94.567244);
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
  };
  
  directionsService.route(request, function (result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    } else {
      alert("Hmm, something went wrong.")
    }
  });
}

About

Practicing using the Google Maps API to build a simple web app that displays the best places to long board in Kansas City.


Languages

Language:JavaScript 43.6%Language:HTML 34.5%Language:CSS 21.9%