Getting Started with Google maps API V3

Source: Internet
Author: User

Since Google is blocked, copy it for reference. Hello, World

The easiest way to get started with Google Maps API is to look at simple examples. The following page shows a map centered on Sydney, New South Wales, Australia:

<!DOCTYPE HTML>  <HTML>    <Head>      <Metaname= "Viewport"content= "initial-scale=1.0, User-scalable=no" />      <styletype= "Text/css">HTML{Height:100%}Body{Height:100%;margin:0;padding:0}#map_canvas{Height:100%}      </style>      <Scripttype= "Text/javascript"src= "Http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">      </Script>      <Scripttype= "Text/javascript">        functionInitialize () {varmapoptions={Center:NewGoogle.maps.LatLng (-34.397, 150.644), Zoom:8, MapTypeId:google.maps.MapTypeId.ROADMAP}; varMap= NewGoogle.maps.Map (document.getElementById ("Map_canvas"), mapoptions); }      </Script>    </Head>    <Bodyonload= "Initialize ()">      <DivID= "Map_canvas"style= "width:100%; height:100%"></Div>    </Body>  </HTML>   

Although this example is simple, note the following:

    1. In this example, the <!DOCTYPE html> application is declared as HTML5 using a declaration.
    2. Use script tags to add Maps API JavaScript.
    3. Create an element named "Map_canvas" div to store the map.
    4. Create Javascript object constants to store several map properties.
    5. Write a JavaScript function to create a "map" object.
    6. body onload initializes the map object by marking the event.

These steps are described below.

Declare your app as HTML5

It is recommended that you declare a real one within your own Web application DOCTYPE . In the example in this article, we use a simple HTML5 to DOCTYPE declare the application as HTML5, as follows:

<! DOCTYPE html>

Most current browsers render content using this claim in "Standard mode" DOCTYPE , which means that your app should have a stronger cross-browser adaptability. It is DOCTYPE also designed to be moderately degraded; browsers that cannot understand the claim ignore it and use compatibility mode to display its contents.

Note that some CSS that works in compatibility mode is not valid in standard mode. Specifically, all sizes expressed as percentages must inherit from the parent block element, and if one of these parent elements does not have a specified size, the system assumes its size as a 0x0 pixel. Therefore, we have added the following <style> statement:

<styletype= "Text/css">HTML{Height:100%}Body{Height:100%;margin:0;padding:0}#map_canvas{Height:100%}  </style>  

The CSS declaration is used to indicate that the map container <div> (named map_canvas ) should occupy the entire height of the HTML body. Please note that we must also make a clear statement and the percentage that is <body> accounted for.

Load Google Maps API
< HTML >    < Head >      <  type= "Text/javascript"        src= "http://maps.googleapis.com/ Maps/api/js?key=your_api_key&sensor=set_to_true_or_false ">      </  Script>  

scriptThe tag contains a URL to the location of the JavaScript file, which loads all the symbols and definitions needed to use the Google Maps API. scriptis a required mark.

keyParameter contains the API key that you applied. Note that this key is not applicable to the V2 API and must be generated through the API console. V3 version is not required.

The URL's sensor parameters (which must be added) are used to indicate whether the app uses sensors such as the GPS locator to determine the user's location. In this example, we set this argument to the variable "Set_to_true_or_false", which emphasizes that you must explicitly set the value to true or false .

HTTPS

If your app is an HTTPS app, you can instead load the Google Maps JavaScript API over https:

<src= "Https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO _true_or_false "    type=" Text/javascript "></script  >  

The Maps API must be loaded over HTTPS in an SSL application to avoid displaying security warnings in most browsers, and it is recommended that you use this practice for applications that contain sensitive user data such as where users are located.

Library

http://maps.googleapis.com/maps/api/jsyou can also choose to load additional libraries using parameters when loading the JavaScript Maps API via URLs libraries . A library is a code module that provides additional functionality to the main JavaScript API, but it is only loaded when you specifically request it.

Asynchronous Load API

You may want to load the Maps API JavaScript code after the page is fully loaded or as needed. To do this, you can insert your own <script> markup as a window.onload response to an event or function call, but you also need to instruct the maps JavaScript API Bootstrapper to execute the application code after the maps JavaScript API code is fully loaded. To do this, you can use a callback parameter that is a variable that the function executes after the API is fully loaded.

The following code indicates that the app loads the maps API (using) after the Web page is fully loaded window.onload , and writes the maps JavaScript API to the markup on that page <script> . In addition, we passed the Maps API Bootstrapper callback=initialize , which instructs the API to execute functions only after it has been fully loaded initialize() :

function Initialize () {    var mapoptions = {      zoom:8,      center:new google.maps.LatLng (-34.397, 150.644), C4/>maptypeid:google.maps.maptypeid.roadmap    }    var map = new Google.maps.Map (document.getElementById ("Map_ Canvas "), mapoptions);  }    function Loadscript () {    var script = document.createelement ("script");    Script.type = "Text/javascript";    SCRIPT.SRC = "Http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=true_or_false &callback =initialize ";    Document.body.appendChild (script);  }    Window.onload = loadscript;  

Map DOM element <div id= "Map_canvas" style= "width:100%; height:100% "></div>

For a map to be displayed on a Web page, we need to set aside a location for it. Typically, we create a named element and div then get a reference to this element in the browser's Document Object Model (DOM).

In the example above, we define a name of "Map_canvas" <div> and use the Style property to set its size. Note that this size is set to "100%", which expands the map to match the screen size of the mobile device. You may need to adjust these values based on your browser's screen size and fill area. Note that the map will always determine its size based on the size of the elements it contains, so you must always <div> set an applicable size explicitly.

Map options
    1. var mapoptions = {    center:new google.maps.LatLng ( -34.397, 150.644),    zoom:8,    Maptypeid: Google.maps.MapTypeId.ROADMAP  };  

To initialize the map, we need to first create an Map options object to contain the map initialization variables. The object is not built, but is created in the form of an object constant.

var mapoptions = {}; Latitude and longitude

Since we want to center set the map center to a specific point, the object is created and the coordinates of the LatLng location are passed in the order of {latitude, longitude} to store the location:

Center = new Google.maps.LatLng (-34.397, 150.644)

The process of converting an address to a geographic location is called geocoding. This version of the Google Maps API supports geocoding. For more information, see geocoding in the Services section of this guide.

Zoom level

The initial resolution of the map display can be zoom set by attributes, where scaling is the 0 lowest level that the Earth map can shrink, and the higher the zoom level, the greater the resolution of the map magnification.

Zoom:8

If you want to provide a map that contains the entire Earth as a single image, you either need a great map, or you need a small map with a lower resolution. As a result, map images within Google maps and maps APIs are divided into two parts: Map tile and zoom level. At low zoom levels, a small group of map tiles can cover a wide area, whereas at high zoom levels, the tiles have a higher resolution and a smaller area of coverage.

Map type

At this point, you must also explicitly set an initial map type.

MapTypeId:google.maps.MapTypeId.ROADMAP

The system supports the following map types:

    • ROADMAPTo display the default, normal 2D tiles for Google maps.
    • SATELLITETo display the captured tiles.
    • HYBRIDTo display tile layers for both captured and important map items (roads, city names).
    • TERRAINFor displaying natural topographic map blocks, which contain elevations and water maps (mountains, rivers, etc.).
Map objects

var map = new Google.maps.Map (document.getElementById ("Map_canvas"), mapoptions);

The JavaScript class that is used to represent the map belongs to the Map class. Objects of this class define a single map on a Web page. (You can create multiple instances of this class, each of which defines a separate map on the Web page.) We new created a new instance of this class using the Javascript operator.

When you create a new map instance, you need to specify an HTML element in the Web page <div> as the container for the map. An HTML node is a document child of a Javascript object, and we document.getElementById() get a reference to that element by means of the method.

This code is used to define a variable (named map ) and then assign it to a new Map object and pass it to the mapOptions option defined by the object constant. These options will be used to initialize the properties of the map. Map()a function is called a "constructor", which is defined as follows:

constructor Function Description
Map(mapDiv:Node, opts?:MapOptions) Creates a new map in a given HTML container (usually a DIV element) with any (optional) arguments passed.
Load map

<body onload= "Initialize ()" >

When an HTML Web page is rendered, the Document Object Model (DOM) is extended, and all external pictures and scripts are received and merged into the document object. To ensure that the system does not place our map on the Web page after it has been fully loaded, we will only <body> onload start executing the function used to build the object after the element of the HTML page receives the event Map . Doing so avoids unexpected behavior and allows us to better control how and when the map is drawn.

bodyThe properties of the tag are onload an example of an event handler. The Google Maps JavaScript API also provides a set of events for you to work with to determine the status change.

Last updated February 1, 2013.

Getting Started with Google maps API V3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.