我正在一个项目中,我需要在给定的城市中显示自行车站,从API检索数据,还需要使用Google Maps API。我遵循了Google文档中的所有内容,但似乎无法显示标记。
我尝试直接在google.maps.Marker中传递自行车站位置参数,但也不会显示。
JavaScript:
class GoogleMap {
constructor(latGmap, lngGmap, zoomGmap) {
this.latGmap = latGmap
this.lngGmap = lngGmap
this.zoomGmap = zoomGmap
this.map = new google.maps.Map(document.getElementById("map"), {
center: { lat: this.latGmap, lng: this.lngGmap },
zoom: this.zoomGmap
})
}
}
class Station {
constructor(stationName, stationStatus, stationAddress, stationAvailableBikes, stationAvailableBikeStands, stationLat, stationLng) {
this.stationName = stationName;
this.stationStatus = stationStatus;
this.stationAddress = stationAddress;
this.stationAvailableBikes = stationAvailableBikes;
this.stationAvailableBikeStands = stationAvailableBikeStands;
this.stationLat = stationLat;
this.stationLng = stationLng;
}
}
const fetchData = async function () {
let dataURL = "https://api.jcdecaux.com/vls/v1/stations?contract=amiens&apiKey=4cb8707fc70c97865d22d1324513f8e6464ed37b";
try {
let response = await fetch(dataURL)
if (response.ok) {
return response.json()
}
else {
console.error('Retour du serveur : ', response.status)
}
} catch (e) {
console.log(e);
}
}
let map;
function initMap() {
let googleMap = new GoogleMap(49.893034, 2.297347, 14);
fetchData().then(data => {
for (i = 0; i < data.length; i++) {
let station = data[i]
let stations = new Station(station.name, station.status, station.address, station.available_bikes, station.available_bike_stands, station.position.lat, station.position.lng)
let lat = stations.stationLat;
let lng = stations.stationLng;
let location = new google.maps.LatLng(lat, lng)
let labels = station.available_bikes.toString();
let marker = new google.maps.Marker({
position: location,
label: labels,
map: map
})
console.log(marker)
}
})
}
HTML:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeMga8sAPw4m43CMWgFu_SNunKJxjyoLg&callback=initMap" type="text/javascript"></script>
使用获取的数据,我应该显示26个标记,但是什么也没有出现。
答案 0 :(得分:0)
在创建标记的位置未定义map
变量(因此不会将其添加到地图中)。
function initMap() {
let googleMap = new GoogleMap(49.893034, 2.297347, 14);
var map = googleMap.map; // or just use googleMap.map where map is being used
// ...
代码段:
class GoogleMap {
constructor(latGmap, lngGmap, zoomGmap) {
this.latGmap = latGmap
this.lngGmap = lngGmap
this.zoomGmap = zoomGmap
this.map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: this.latGmap,
lng: this.lngGmap
},
zoom: this.zoomGmap
})
}
}
class Station {
constructor(stationName, stationStatus, stationAddress, stationAvailableBikes, stationAvailableBikeStands, stationLat, stationLng) {
this.stationName = stationName;
this.stationStatus = stationStatus;
this.stationAddress = stationAddress;
this.stationAvailableBikes = stationAvailableBikes;
this.stationAvailableBikeStands = stationAvailableBikeStands;
this.stationLat = stationLat;
this.stationLng = stationLng;
}
}
const fetchData = async function() {
let dataURL = "https://api.jcdecaux.com/vls/v1/stations?contract=amiens&apiKey=4cb8707fc70c97865d22d1324513f8e6464ed37b";
try {
let response = await fetch(dataURL)
if (response.ok) {
return response.json()
} else {
console.error('Retour du serveur : ', response.status)
}
} catch (e) {
console.log(e);
}
}
let map;
function initMap() {
let googleMap = new GoogleMap(49.893034, 2.297347, 14);
var map = googleMap.map;
fetchData().then(data => {
for (i = 0; i < data.length; i++) {
let station = data[i]
let stations = new Station(station.name, station.status, station.address, station.available_bikes, station.available_bike_stands, station.position.lat, station.position.lng)
let lat = stations.stationLat;
let lng = stations.stationLng;
let location = new google.maps.LatLng(lat, lng)
let labels = station.available_bikes.toString();
let marker = new google.maps.Marker({
position: location,
label: labels,
map: map
})
console.log(marker)
}
})
}
/* 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;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
答案 1 :(得分:0)
这是我开设的类似课程,欢迎您适应
/**
* 'GMap'
* extends googlemaps to allow simpler coding in other apps, should be loaded after the main google maps
* a new instance of a google map is contructed calling this with identical arguments to the standard class and then returned
* the map name must be unique and reserved as a global by the client code, eg var pagemap outside of function, so the external callbacks
* can use this name to run a function against, eg pagemap.queryMove_do
*
*/
class GMap {
constructor(parentElem, args) {
this.geocoder = new google.maps.Geocoder();
this.markers = {};
this.markerbounds = new google.maps.LatLngBounds();
var args = model.array_defaults(args,
{
instanceName: "gMap",
mapID: "mapFrame",
address: null,//address will override center
center: new google.maps.LatLng(51.509865, -0.118092),
zoom: 9,
minzoom: 15,
maxzoom: 21
})
this.name = args.instanceName;
$("#" + parentElem).prepend("<div id='" + args.mapID + "' class='mapframe'></div>");
this.map = new google.maps.Map(document.getElementById(args.mapID), args);
if (args.address) {
this.panToAddress(args.address);
}
}
getAddressLocation(id, query, callback) {
this.geocoder.geocode({"address": query}, function (results, status) {
if (status == "OK") {
location = {lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()};
}
else {
var location = null;
}
eval(callback + "(" + id + ",status,location)");
});
}
setMarker(title, location, optargs) {
optargs=model.array_defaults(optargs,{
infowindow:false,
label:{},
zIndex: 0,
icon: "/DD_libmedia/images/icons/white-red-dot.png"//source: https://commons.wikimedia.org/wiki/File:Red_circle_(thin).svg
});
if (optargs.infowindow) {
var infocontent = "<div id='" + optargs.infowindow.id + "' class='infowindowFrame'><h5>" + optargs.infowindow.title + "</h5>" + optargs.infowindow.content + "<br />";
for (var b in optargs.infowindow.buttons) {
var button= view.getBtnCFG(
optargs.infowindow.buttons[b]
);
infocontent +=button.dhtml;
}
infocontent += "</div>";
var infowindow = new google.maps.InfoWindow({
content: infocontent
});
}
var markericon = {
scaledSize: new google.maps.Size(25, 25),
url: optargs.icon
};
var markerposition = {lat: location.lat, lng: location.lng};
var marker = new google.maps.Marker({
title: title,
label:optargs.label,
position: markerposition,
map: ctrl.map.map,
icon: markericon,
zIndex: optargs.zIndex,
animation: google.maps.Animation.DROP
});
this.markerbounds.extend(markerposition);
if (optargs.infowindow) {
marker.addListener('click', function () {
infowindow.open(ctrl.map.map, marker);
});
}
}
/**
* zoomToMarkers
* where markers have been set with this.setMarker then zoomToMarkers will zoom the map to the marker boundaries
* see: https://en.wikipedia.org/wiki/Decimal_degrees
*
* LAT
* + is north of the equator, - is south of the equator
*
* LNG
* + is east of Greenwich
* - is west of Greenwich
*
* Latitude and longitude are usually expressed in that sequence, latitude before longitude.
*/
zoomToMarkers() {
this.map.fitBounds(this.markerbounds, {bottom: 2, left: 2, right: 2, top: 2});
}
panTo(latLng,zoomlevel){
this.map.panTo(latLng);
this.map.setZoom(zoomlevel);
}
panToAddress(address) {
this.geocoder.geocode({"address": address}, function (results, status) {
//xonservice.gotLocation(results, status);
});
}
}