📅  最后修改于: 2023-12-03 14:41:36.166000             🧑  作者: Mango
Google Maps JS is a popular way to add maps and location-based services to your web applications. One of the key features of Google Maps JS is the ability to load data onto the map when it loads, such as markers, polygons, and other features. In this tutorial, we'll cover how to load data onto a Google Map when it loads using Javascript.
Before we start, you'll need a few things:
In order to add data to a Google Map on load, we'll need to use the addListenerOnce()
function to wait for the map to finish loading, and then add our data to the map. Here's an example:
google.maps.event.addListenerOnce(map, 'idle', function(){
// Add your code to add data to the map here
});
In this code, we're using the addListenerOnce()
function to listen for the idle
event, which fires when the map has finished loading. Once the event fires, our function will execute, and we can then add data to the map using the map
variable.
google.maps.event.addListenerOnce(map, 'idle', function(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37.774929, -122.419416),
map: map,
title: 'San Francisco'
});
});
In this example, we're adding a marker to our map, positioned at the coordinates for San Francisco. We pass the map
variable to the marker as the map on which it should be displayed.
google.maps.event.addListenerOnce(map, 'idle', function(){
var polygon = new google.maps.Polygon({
paths: [
new google.maps.LatLng(37.774929, -122.419416),
new google.maps.LatLng(37.774929, -122.529416),
new google.maps.LatLng(37.664929, -122.529416),
new google.maps.LatLng(37.664929, -122.419416)
],
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
polygon.setMap(map);
});
In this example, we're adding a polygon to our map, with vertices at the coordinates for San Francisco. We set the strokeColor
, strokeOpacity
, strokeWeight
, fillColor
, and fillOpacity
properties to customize the appearance of the polygon.
In this tutorial, we've covered how to add data to a Google Map when it loads using Javascript. By using the addListenerOnce()
function, we can wait for the map to finish loading and then execute code to add data to the map. This opens up a lot of possibilities for customizing the appearance and functionality of maps in your web applications.