【问题标题】:Google Maps marker won't display谷歌地图标记不会显示
【发布时间】:2019-12-09 23:07:52
【问题描述】:

我正在开展一个项目,我需要在给定城市中显示自行车站,从 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 个标记,但什么都没有出现。

【问题讨论】:

    标签: javascript google-maps google-maps-markers


    【解决方案1】:

    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
      // ...
    

    proof of concept fiddle

    代码 sn-p:

    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>

    【讨论】:

      【解决方案2】:

      这里有一个类似的课,欢迎大家改编

      /**
       *    '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);
              });
          }
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-14
        • 2017-07-17
        • 2015-03-14
        • 1970-01-01
        • 2014-10-08
        相关资源
        最近更新 更多