如何在谷歌地图pin上添加标记

How to add marker on google map pin

本文关键字:添加 加标记 pin 谷歌地图      更新时间:2024-01-13

我正试图在我的谷歌地图上添加一个标记,但由于某种原因,它没有出现。地图本身运行良好,但标记不会显示。我正在遵循googleapi文档,所有其他可定制的功能都很好。我也尝试过手动添加Lon和Lat,但没有。我确信我忽略了一些简单的事情,但我不确定它是什么,任何帮助都将不胜感激。提前谢谢。

<% if @location.latitude.present? && @location.longitude.present? %>
    <script>
    function initMap() {
    // Specify features and elements to define styles.
    var styleArray = [
      {
        featureType: "all",
        stylers: [
         { saturation: -80 }
        ]
      },{
        featureType: "road.arterial",
        elementType: "geometry",
        stylers: [
          { hue: "#00ffee" },
          { saturation: 50 }
        ]
      },{
        featureType: "poi.business",
        elementType: "labels",
        stylers: [
          { visibility: "off" }
        ]
      }
    ];
    var myLatLng = {lat: <%= @location.latitude %>, lng: <%= @location.longitude %>};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      // styles: styleArray,
      center: myLatLng
    });
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: <%= @location.name %>
    });
    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?   signed_in=true&callback=initMap">
    </script>
    <div id="map"></div>
   <% end %>

您似乎没有设置位置

 var marker = new google.maps.Marker({
  position: markerPos,
  map: map,
  title: <%= @location.name %>
});

markerPos..的值在哪里。。?

try with myLatLng

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  title: <%= @location.name %>
});

只是为了调试,请在没有位置的情况下尝试。名称

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map
});

问题就在这里:

var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: <%= @location.name %>
    });

您正在输出location.name,但它需要在一个带引号的字符串中。现在,如果您查看源代码并看到客户端代码,我认为它看起来像:

var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: Hello World
    });

你可能会得到一个JS错误。试试看:

var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: '<%= @location.name %>'
    });