Add marker with Google Maps Javascript API to look exactly as marker that were added in maps.google.com

前端 未结 1 1076
走了就别回头了
走了就别回头了 2020-11-30 10:33

I am trying to add map to my site using Google Maps Javascript API. I want it to looks exactly like map that was created with maps.google.com:

But I can not

相关标签:
1条回答
  • 2020-11-30 11:07

    To customize the label text see the documentation for the markerLabel anonymous object. To control the position of the label, you need to use the Icon labelOrigin property.

    var marker = new google.maps.Marker({
      position: coordinates,
      map: map,
      icon: {
        url: "http://maps.google.com/mapfiles/ms/icons/red-dot.png",
        labelOrigin: new google.maps.Point(75, 32),
        size: new google.maps.Size(32,32),
        anchor: new google.maps.Point(16,32)
      },
      label: {
        text: "5409 Madison St",
        color: "#C70E20",
        fontWeight: "bold"
      }
    });
    

    To add the "red dot" ("measle") at the bottom of the marker, the simplest way is to create another marker at the same location (although you could create an icon for your marker that includes both the measle and the default red "bubble" marker).

    var measle = new google.maps.Marker({
      position: coordinates,
      map: map,
      icon: {
        url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
        size: new google.maps.Size(7, 7),
        anchor: new google.maps.Point(4, 4)
      }
    });
    

    proof of concept fiddle

    code snippet:

    function initMap() {
      var coordinates = {
        lat: 40.785845,
        lng: -74.020496
      };
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 14,
        center: coordinates,
        scrollwheel: false
      });
      var measle = new google.maps.Marker({
        position: coordinates,
        map: map,
        icon: {
          url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
          size: new google.maps.Size(7, 7),
          anchor: new google.maps.Point(3.8, 3.8)
        }
      });
      var marker = new google.maps.Marker({
        position: coordinates,
        map: map,
        icon: {
          url: "http://maps.google.com/mapfiles/ms/icons/red-dot.png",
          labelOrigin: new google.maps.Point(75, 32),
          size: new google.maps.Size(32, 32),
          anchor: new google.maps.Point(16, 32)
        },
        label: {
          text: "5409 Madison St",
          color: "#C70E20",
          fontWeight: "bold"
        }
      });
    }
    google.maps.event.addDomListener(window, "load", initMap);
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="map"></div>

    0 讨论(0)
提交回复
热议问题