Google Maps Javascript Api Drawing Tools
The Maps JavaScript API lets you custom-make maps with your own content and imaging for display on web pages and mobile devices. The Maps JavaScript API features quaternary alkalic map types (roadmap, satellite, hybrid, and terrain) which you can modify using layers and styles, controls and events, and various services and libraries.
Audience
This corroboration is designed for people comrade with JavaScript programming and object-oriented programming concepts. You should also represent familiar with Google Maps from a exploiter's standpoint. At that place are many another JavaScript tutorials available happening the Web.
This conceptual documentation is designed to let you quickly start exploring and developing applications with the Maps JavaScript API. We also publish the Maps JavaScript API Reference.
Hello, World
The easiest way to start encyclopaedism about the Maps JavaScript API is to realise a simple exemplar. The following representative displays a map centralised on Sydney, New Southerly Wales, Australia.
TypeScript
get map: google.maps.Map; purpose initMap(): void { map = hot google.maps.Map(written document.getElementById("map") as HTMLElement, { center: { latisimus dorsi: -34.397, lng: 150.644 }, zoom: 8, }); }
JavaScript
let map; function initMap() { mapping = novel Google.maps.Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); }
CSS
/* Always set the map height explicitly to define the size of the div * element that contains the mapping. */ #map { summit: 100%; } /* Nonmandatory: Makes the sample page fill the window. */ hypertext mark-up language, consistence { meridian: 100%; margin: 0; padding: 0; }
HTML
<!DOCTYPE html> <html> <head> <title of respect>Simple Map</title of respect> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></book> <link rel="stylesheet" type="text/css" href="./style.css" /> <script src="./index.js"></script> </maneuver> <body> <div id="map"></div> <!-- Async hand executes directly and must be after some DOM elements secondhand in callback. --> <script src="https://maps.googleapis.com/maps/api/js?tonality=YOUR_API_KEY&callback=initMap&adenylic acid;v=weekly" async ></script> </body> </hypertext markup language>
Reckon deterrent example
let map; role initMap() { map = early Google.maps.Map(document.getElementById("map"), { center: { latisimus dorsi: -34.397, lng: 150.644 }, soar upwards: 8, }); }
/* Always set the mapping height explicitly to specify the size up of the div * ingredient that contains the map. */ #map { acme: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; leeway: 0; padding: 0; }
<!DOCTYPE html> <hypertext mark-up language> <head> <title>Simple Correspondenc</title> <playscript 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 plan any DOM elements utilized in recall. --> <handwriting src="https://maps.googleapis.com/maps/api/js?winder=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=time period&A;channel=2" async ></script> </body> </HTML>
Try Sample
Even out in that simple example, there are a a couple of things to note:
- We declare the application equally HTML5 exploitation the
<!DOCTYPE html>
declaration. - We create a
div
chemical element named "map out" to hold the map. - We define a JavaScript occasion that creates a map in the
div
. - We encumbrance the Maps JavaScript API using a
script
tag.
These steps are explained below.
Declaring your application as HTML5
We recommend that you declare a true DOCTYPE
within your entanglement lotion. Within the examples hither, we've declared our applications arsenic HTML5 using the simple HTML5 DOCTYPE
American Samoa shown below:
<!DOCTYPE html>
To the highest degree incumbent browsers will fork over content that is announced with this DOCTYPE
in "standards mode" which means that your covering should live more cross-browser compliant. The DOCTYPE
is besides intentional to degrade graciously; browsers that don't understand it will ignore it, and exercise "quirks mode" to display their content.
Note that some CSS that works within quirks mode is not sensible in standards mode. In specific, all percentage-based sizes must inherit from parent block elements, and if any of those ancestors fail to destine a sized, they are assumed to make up sized at 0 x 0 pixels. For that reason, we include the following <style>
declaration:
<style> #map { height: 100%; } HTML, body { height: 100%; margin: 0; padding: 0; } </style>
This CSS contract indicates that the map container <div>
(with ID map
) should take up 100% of the height of the Hypertext mark-up language body. Note that we must specifically announce those percentages for <body>
and <html>
likewise.
Loading the Maps JavaScript API
The Maps JavaScript API is pie-eyed using a script
chase, which can exist added inline in your HTML file OR dynamically using a separate JavaScript file. We recommend that you review both approaches, and choose the one that is nearly appropriate for how the code in your project is structured.
Inline Consignment
To load the Maps JavaScript API inline in an HTML file, contribute a book
tag as show below.
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script>
Dynamic Load
To dynamically load the Maps JavaScript API inline exploitation a separate JavaScript file away, see the example at a lower place. This approach allows you to handgrip all of your code for impermanent with the API from a class .js
file, and is the combining weight of adding the script tag inline.
// Create the script tag, set the pertinent attributes var script = document.createElement('script'); handwriting.src = 'https://maps.googleapis.com/maps/api/js?paint=YOUR_API_KEY&callback=initMap'; script.async = true; // Attach your recall office to the `windowpane` object window.initMap = function() { // JS API is crocked and available }; // Append the 'playscript' element to 'head' written document.head.appendChild(script);
High-power Loading
The @googlemaps/js-api-loader package is available to make a to a greater extent seamless dynamic loading experience. It fire be installed through and through NPM with the succeeding:
npm put in @googlemaps/js-api-stevedore
This box can be imported into the diligence with:
import { Loader } from "@googlemaps/js-api-loader"
The loader exposes a Promise and callback interface. The following demonstrates usage of the default Promise method load()
.
TypeScript
const loader = new Loader({ apiKey: "YOUR_API_KEY", version: "weekly", ...additionalOptions, }); loader.load().then(() => { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { center: { latisimus dorsi: -34.397, lng: 150.644 }, zoom: 8, }); });
JavaScript
const loader = new Loader({ apiKey: "YOUR_API_KEY", version: "weekly", ...additionalOptions, }); loader.load().then(() => { map = new google.maps.Represent(document.getElementById("map out"), { concentrate on: { lat: -34.397, lng: 150.644 }, whizz: 8, }); });
Script Tag Attributes
Notice in the examples supra that several attributes are set on the `script` give chase, which are recommended. The following is an explanation of each attribute.
-
src
: The URL where the Maps JavaScript API is soused from, including all of the symbols and definitions you need for using the Maps JavaScript API. The Universal resource locator in that example has two parameters:tonality
, where you provide your API key, andcallback
, where you fix the name of a world function to be called once the Maps JavaScript API lots completely. Learn many about Uniform resource locator parameters. -
async
: Asks the browser to asynchronously download and execute the script. When the playscript is executed, it will call the function specified using thecallback
parameter.
Libraries
When loading the Maps JavaScript API via the URL you may optionally onus extra libraries through utilization of the libraries
URL parameter. Libraries are modules of cipher that render additional functionality to the main Maps JavaScript API but are not loaded unless you specifically bespeak them. For more information, see Libraries in the Maps JavaScript API.
Synchronously loading the API
In the handwriting
tag that loads the Maps JavaScript API, it is possible to omit the defer
property and the callback
parameter. This will cause the consignment of the API to block until the API is downloaded.
This will probably slow your page load. But it means you can write subsequent script tags assuming that the API is already loaded.
Map DOM Elements
<div id="map"></div>
For the map to show on a web foliate, we must reserve a bit for it. Commonly, we do this by creating a named div
element and obtaining a reference to this constituent in the browser's document object mock up (DOM).
In the deterrent example above, we used CSS to set the height of the map out div to "100%". This will exposit to fit the sized on mobile devices. You may need to adjust the width and acme values based on the browser's screensize and padding. Note that divs usually undergo their breadth from their containing element, and empty divs commonly sustain 0 height. For this intellect, you must always set a superlative happening the <div>
explicitly.
Map Options
There are deuce needed options for every map: center
and zoom
.
map = new Google.maps.Map(text file.getElementById('mapping'), { center: {latisimus dorsi: -34.397, lng: 150.644}, zoom: 8 });
Zoom Levels
The initial resolution at which to display the map is fixed by the zoom
property, where zoom along 0
corresponds to a map of the Earth in full zoomed out, and larger zoom levels zoom in at a higher resolving.
rapid climb: 8
Oblation a map of the smooth Earth As a azygos image would either require an immense correspondenc, or a small map with very low resolution. As a result, map images within Google Maps and the Maps JavaScript API are broken up into map "tiles" and "whizz along levels." At low zoom levels, a micro set of map tiles covers a wide country; at higher zoom levels, the tiles are of high resolution and cover a smaller area. The following list shows the approximate storey of detail you can have a bun in the oven to project at all zoom level:
- 1: World
- 5: Landmass/continent
- 10: City
- 15: Streets
- 20: Buildings
The following three images reflect the unvaried location of Tokyo at zoom levels 0, 7 and 18.
For information on how the Maps JavaScript API loads tiles founded connected the current zoom level, see the guide to map and tile coordinates.
The Map Physical object
map = new Google.maps.Map(document.getElementById("map"), {...});
The JavaScript class that represents a map is the Map
class. Objects of this class delimit a single map on a page. (You may create more than one instance of this classify — each object will define a separate map on the page.) We make over a new illustrate of this social class using the JavaScript new
operator.
When you create a new map instance, you set apart a <div>
HTML element in the page as a container for the map. Hypertext markup language nodes are children of the JavaScript document
objective, and we obtain a reference to this element via the written document.getElementById()
method.
This code defines a variable (named map
) and assigns that shifting to a spick-and-span Map
object. The serve Map()
is known as a constructor and its definition is shown below:
Builder | Description |
---|---|
Represent(mapDiv:Thickening, opts?:MapOptions ) | Creates a new map inside of the given HTML container — which is typically a DIV element — using any (optional) parameters that are passed. |
Troubleshooting
API Key and Billing Errors
Under certain destiny, a old map, or 'negative' Street Take i icon, watermarked with the text "for development purposes only", may be displayed. This behavior typically indicates issues with either an API key or billing. In order to use Google Maps Platform products, billing must be enabled on your account, and all requests must admit a valid API key. The following flow from volition help troubleshoot this:
If your code isn't working:
To help you get your maps code up and running, Brendan Kenny and Mano Simon Marks manoeuver out some common mistakes you bet to fix them in this video.
- Look for typos. Recollect that JavaScript is a pillowcase-medium linguistic communication.
- Ascertain the basics - some of the most common problems occur with the initial map creation. So much Eastern Samoa:
- Confirm that you've mere the
whizz along
andcenter
properties in your map options. - Ensure that you have declared a div element in which the map out will appear on the screen.
- Ensure that the div element for the correspondenc has a height. By default, div elements are created with a pinnacle of 0, and are therefore ultraviolet.
- Confirm that you've mere the
- Use a JavaScript debugger to avail discover problems, like the one available in the Chrome Developer Tools. Start by looking in the JavaScript console for errors.
- Post questions to Sight Overflow. Guidelines on how to Wiley Post great questions are available on the Livelihood page.
Places Library
Offer comprehensive Place data and features to enrich your app with the Maps JavaScript API, including Place Autocomplete, Place inside information, Place Search, and more.
Learn much
Google Maps Javascript Api Drawing Tools
Source: https://developers.google.com/maps/documentation/javascript/overview
0 Response to "Google Maps Javascript Api Drawing Tools"
Post a Comment