Содержание
- 1 Поделиться собственной картой
- 2 The Map Object
- 3 Delete Location History
- 4 Universal cross-platform syntax
- 5 Сервис Art Project
- 6 Troubleshooting
- 7 Loading the Maps JavaScript API
- 8 Hello, World
- 9 Map Options
- 10 Двигаться легко
- 11 More examples
- 12 На шаг впереди
- 13 Новое приложение Google Карты для Android, iPhone
- 14 Легко узнать, как выглядит место в которое вы направляетесь
- 15 Declaring your application as HTML5
- 16 Можно даже побывать на луне
- 17 See your travels
- 18 Map DOM Elements
- 19 Launch Google Maps and perform a specific action
- 20 Забудьте о пробках
- 21 Шагайте в ногу со временем
- 22 Edit Timeline
- 23 Remove photos
- 24 Delete a day
- 25 Расскажите о своих впечатлениях
Поделиться собственной картой
The Map Object
map = new google.maps.Map(document.getElementById("map"), {...});
The JavaScript class that represents a map is the class.
Objects of this class define a single map on a page. (You may create more
than one instance of this class — each object will define a separate
map on the page.) We create a new instance of this class using the JavaScript
operator.
When you create a new map instance, you specify a
HTML element in the page as a container for the map. HTML nodes
are children of the JavaScript object, and
we obtain a reference to this element via the
method.
This code defines a variable (named ) and assigns that
variable to a new object. The function is
known as a constructor and its definition is shown below:
Constructor | Description |
---|---|
Creates a new map inside of the given HTML container — which is typically a DIV element — using any (optional) parameters that are passed. |
Delete Location History
You can delete all or part of your Location History.Important: When you delete information from Timeline, it’s permanent. You won’t be able to see your Location History information on Timeline again. If you have other settings like Web & App Activity turned on and you delete Location History, you may still have location data saved in your Google Account as part of your use of other Google sites, apps, and services. For example, location data may be saved as part of activity on Search and Maps when your Web & App Activity setting is on, and included in your photos depending on your camera app settings.
To delete Location History, follow the steps below.
- On your computer, go to Timeline.
- In the bottom right, click Delete . You can also click Settings Delete all location history.
- Click Delete location history.
Automatically delete your Location History
You can choose to automatically delete Location History that’s older than 3 months or 18 months.
- On your computer, go to Timeline.
- At the bottom right, click Settings Automatically delete Location History.
- Follow the on-screen instructions.
Universal cross-platform syntax
As a developer of an Android app, an iOS app, or a website, you can construct a common URL,
and it will open Google Maps and perform the requested action, no matter the platform in
use when the map is opened.
- On an Android device:
- If
Google Maps app for Android is installed and active, the URL launches
Google Maps in the Maps app and performs the requested action. - If the Google Maps app is not installed or is disabled, the URL launches
Google Maps in a browser and performs the requested action.
- If
- On an iOS device:
- If Google Maps app for iOS
is installed, the URL launches Google Maps in the Maps app and performs
the requested action. - If the Google Maps app is not installed, the URL launches
Google Maps in a browser and performs the requested action.
- If Google Maps app for iOS
- On any other device, the URL launches Google Maps in a browser and
performs the requested action.
It is recommended that you use a cross-platform URL to launch Google Maps from your app
or website, since these universal URLs allow for broader handling of the maps requests
no matter the platform in use. For features that may only be functional on a mobile
platform (for example, turn-by-turn navigation), you may prefer to use a platform-specific
option for Android or iOS. See the following documentation:
-
Google Maps Intents for Android — specifically to launch the
Google Maps app for Android
-
Google Maps URL Scheme for iOS — specifically to launch the
Google Maps app for iOS
Сервис Art Project
Troubleshooting
API Key and Billing Errors
Under certain circumstances, a darkened map, or ‘negative’ Street View image,
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 include a valid API key. The following flow will help troubleshoot this:
If your code isn’t working:
To help you get your maps code up and running, Brendan Kenny and Mano Marks point out
some common mistakes and how to fix them in this video.
- Look for typos. Remember that JavaScript is a case-sensitive
language. - Check the basics — some of the most common problems occur with the
initial map creation. Such as:- Confirm that you’ve specified the
and properties in your map
options. - Ensure that you have declared a div element in which the map will
appear on the screen. - Ensure that the div element for the map has a height. By default,
div elements are created with a height of 0, and are therefore
invisible.
Refer to our examples for a
reference
implementation. - Confirm that you’ve specified the
- Use a JavaScript debugger to help identify problems, like the one available
in the Chrome
Developer Tools. Start by looking in the JavaScript console for errors. - Post questions to Stack
Overflow. Guidelines on how to post great questions are available on
the Support page.
Loading the Maps JavaScript API
Script Tag Attributes
-
: The URL where the Maps JavaScript API is loaded from,
including all of the symbols and definitions you need for using the Maps JavaScript API.
The URL in this example has two parameters: , where you
provide your API key, and , where you specify the name
of a global function to be called once the Maps JavaScript API
loads completely. Read more about URL parameters. -
: Asks the browser to parse the HTML document first before loading the script.
When the script is executed, it will call the function specified using the
parameter.
HTTPS or HTTP
We think security on the web is pretty important, and recommend using HTTPS
whenever possible. As part of our efforts to make the web more secure, we’ve
made all of the Maps JavaScript API available over HTTPS. Using HTTPS
encryption makes your site more secure, and more resistant to snooping or tampering.
We recommend loading the Maps JavaScript API over HTTPS using the
tag provided above.
If required, you can load the Maps JavaScript API over HTTP by
requesting .
Libraries
When loading the Maps JavaScript API via the URL you may optionally
load additional libraries through use of the
URL parameter. Libraries are modules of code that
provide additional functionality to the main Maps JavaScript API but are not
loaded unless you specifically request them. For more
information, see
Libraries in the Maps JavaScript API.
Synchronously loading the API
In the tag that loads the Maps JavaScript API,
it is possible to omit the attribute and the
parameter. This will cause the loading 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.
Hello, World
View example
let map;
function initMap() {
map = new google.maps.Map(document.getElementById(«map»), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src=»https://polyfill.io/v3/polyfill.min.js?features=default»></script>
<script
src=»https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initMap&libraries=&v=weekly»
defer
></script>
<!— jsFiddle will insert css and js —>
</head>
<body>
<div id=»map»></div>
</body>
</html>
Even in this simple example, there are a few things to note:
- We declare the application as HTML5 using the declaration.
- We create a element named «map» to hold the
map. - We define a JavaScript function that creates a map in the
. - We load the Maps JavaScript API using a tag.
These steps are explained below.
Map Options
There are two required options for every map: and
.
map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 });
Zoom Levels
The initial resolution at which to display the map is set by the
property, where zoom
corresponds to a map of the Earth fully zoomed out, and larger zoom levels
zoom in at a higher resolution. Specify zoom level as an integer.
zoom: 8
Offering a map of the entire Earth as a single image would either
require an immense map, 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 «zoom levels.» At low zoom levels, a small set of
map tiles covers a wide area; at higher zoom levels, the tiles are of
higher resolution and cover a smaller area. The following list shows the
approximate level of detail you can expect to see at each zoom level:
- 1: World
- 5: Landmass/continent
- 10: City
- 15: Streets
- 20: Buildings
The following three images reflect the same location of Tokyo
at zoom levels 0, 7 and 18.
For information on how the Maps JavaScript API loads
tiles based on the current zoom level, see the guide to
.
Двигаться легко
На вашем пути больше не будет никаких преград. Одна из главных особенностей сервиса, идеально подходящая для жителей крупных городов, — интерактивное отслеживание ситуации на дорогах. В отличие от остальных навигаторов, Гугл-карты не просто строят статичный маршрут.
Детализация маршрута с гугл картами
Приложение умеет не просто анализировать дорожную загрузку, но и менять результаты в соответствии с полученной информацией. Если ваш маршрут пролегает по дороге, которая сейчас стоит вследствие крупной аварии, приложение порекомендует вам перестроить путь и проехаться по маленькой боковой улочке.
Вы также можете изменить путь самостоятельно. Если автомобилисты в соседней пробке при помощи чата порекомендовали вам проехать под мостом, скорректируйте выстроенный маршрут в соответствии с их советами.
More examples
На шаг впереди
Нередко начинающие автолюбители неуверенно чувствуют себя на дороге
Все их внимание уходит на отслеживание текущей ситуации. Времени следить за маршрутом уже не остается
Из-за этого новички нередко пропускают нужный поворот или съезд, вынуждены терять время, перестраиваться в другой ряд и возвращаться.
Гугл карты помогут проложить обратный маршрут
С Гугл-картами такая проблема исчезает. В приложении есть возможность включить опцию пошаговой навигации. В этом случае сервис будет заранее сообщать вам, что через несколько метров нужно повернуть направо. На карте появится крупная отметка, а роботизированный голос будет регулярно напоминать вам о повороте.
Помимо этого, в сервисе присутствует интерактивный выбор полосы движения. Сайт порекомендует, в какой ряд лучше перестроиться, и даст совет в зависимости от сделанного выбора.
Новое приложение Google Карты для Android, iPhone
Легко узнать, как выглядит место в которое вы направляетесь
Declaring your application as HTML5
We recommend that you declare a true
within your web application. Within the examples here, we’ve
declared our applications as HTML5 using the simple HTML5
as shown below:
<!DOCTYPE html>
Most current browsers will render content that is declared with this
in «standards mode» which means that your application
should be more cross-browser compliant. The is also
designed to degrade gracefully; browsers that don’t understand it will ignore
it, and use «quirks mode» to display their content.
Note that some CSS that works within quirks mode is not valid in
standards mode. In specific, all percentage-based sizes must inherit
from parent block elements, and if any of those ancestors fail to
specify a size, they are assumed to be sized at 0 x 0 pixels. For
that reason, we include the following
declaration:
<style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } </style>
This CSS declaration indicates that the map container
(with id ) should take up 100% of the height of the HTML
body. Note that we must specifically declare those percentages for
and as well.
Можно даже побывать на луне
See your travels
You can see how far you travelled and the way you travelled from place to place, like walking, biking, driving, or public transportation. Whether Timeline measures distances in miles or kilometers is based on your country.
- On your computer, open Google Maps.
- Sign in with the same Google Account you use on your mobile device.
- In the top left, click Menu .
- Click Timeline .
- To see another date, at the top, choose a day, month, and year.
Tip: To see places that you’ve visited recently, click Menu Your places Visited.
See your home and work on Timeline
If you’ve saved your home and work addresses, they’ll show up on Timeline. In addition to Timeline, this information may also be used in other Google products and services.
Learn how to set your home and work addresses.
Map DOM Elements
<div id="map"></div>
For the map to display on a web page, we must reserve a spot for it.
Commonly, we do this by creating a named element and
obtaining a reference to this element in the browser’s document object model
(DOM).
In the example above, we used CSS to set the height of the map div to
«100%». This will expand to fit the size on mobile devices. You may need to
adjust the width and height values based on the browser’s screensize and
padding. Note that divs usually take their width from their containing
element, and empty divs usually have 0 height. For this reason, you must
always set a height on the explicitly.
Launch Google Maps and perform a specific action
To launch Google Maps and optionally perform one of the supported functions,
use a URL scheme of one of the following forms, depending on the action requested:
-
— launch a Google Map that displays a pin for a specific place, or perform
a general search and launch a map to display the results: -
— request directions and launch Google Maps with the results:
-
— launch Google Maps with no markers or directions:
-
— launch an interactive panorama image:
Important: The parameter identifies the version of
Maps URLs this URL is intended for. This parameter is required in every
request. The only valid value is 1. If is NOT present in the URL,
all parameters are ignored and the default Google Maps app will launch, either
in a browser or the Google Maps mobile app, depending on the platform in use
(for example, https://www.google.com/maps).
Constructing valid URLs
You must properly encode URLs.
For example, some parameters use a pipe character
() as a separator, which you must encode as
in the final URL. Other parameters use comma-separated values, such as latitude/longitude
coordinates or City, State. You must encode the comma as . Encode spaces with
, or replace them with a plus sign ().
Additionally, URLs are limited to 2,048 characters for each request. Be aware of this limit
when constructing your URLs.
Забудьте о пробках
Шагайте в ногу со временем
Главная особенность данного сервиса – высокая интеграция с остальными приложениями от Гугл. Современная поисковая система собирает много информации о пользователях. У организации уже есть наш круг интересов, список возможных потребностей. Более того, компания зачастую знает, где мы живем.
Гугл карты адаптируются для вас
Но вся эта информация не используется нам во вред. Напротив, используя собранные поисковыми роботами данные Гугл адаптирует результаты выдачи специально для нас. Если вы зайдете на карту, она автоматически определит ваше местоположение и откроет конкретное государство и город.
Edit Timeline
If a place is wrong on Timeline, you can edit the location and when you were there. To do this, turn on Web & App Activity:
- On your computer, go to Timeline.
- Find the place you want to change on Timeline and click the Down arrow .
- Choose the correct place or search for a place in the search box.
- To edit when you were there, click the time.
Note: If Web & App Activity is turned off, you won’t be able to edit locations or activities on Timeline, but you can delete a day or your entire Location History.
Find Google Photos in Timeline
You can view your Google Photos in Timeline. To control whether your Google Photos appear in Timeline or not, follow these steps:
- On your computer, go to Timeline.
- At the bottom right, click Settings Timeline settings.
- Under «Timeline» find «Google Photos.»
- To stop photos from showing up on Timeline, make sure the switch is off.
- To show photos on Timeline, make sure the switch is on.
Tip: You can remove photos from Timeline, but this will not result in them or their metadata being deleted from Google Photos.
Remove photos
Photos show up on Timeline when they’re uploaded to Google Photos. You can delete photos from Timeline, but they won’t be deleted from Google Photos.
- On your computer, go to Timeline.
- In the top right of the photo, click the check mark for each photo you want to delete.
- Choose Remove photo.
Delete a day
Important: When you delete information from Timeline, it’s permanent. You won’t be able to see your Location History information on Timeline again. If you have other settings like Web & App Activity turned on and you delete Location History, you may still have location data saved in your Google Account as part of your use of other Google sites, apps, and services. For example, location data may be saved as part of activity on Search and Maps when your Web & App Activity setting is on, and included in your photos depending on your camera app settings.
- On your computer, go to Timeline.
- Click on the day you want to delete.
- In the panel on the left, go to the top right and click Delete .
- Choose Delete day.