How to add marker on google map pin

时间:2016-04-04 18:46:34

标签: javascript google-maps google-maps-api-3

I'm trying to add a marker to my google maps and for some reason its not showing up. The map itself is working fine, but the marker will not display. I'm following the google api documentation, and all the other customizable features work fine. I have also tried manually adding the Lon and Lat, but nothing. I'm sure its something simple I'm overlooking but I'm not sure what it is, any help would be much appreciated. Thanks in advance.

<% 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 %>

2 个答案:

答案 0 :(得分:2)

seems you not have setted the position

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

Where is the value for markerPos ..?

try with myLatLng


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

And just for debugging try without location.name

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

答案 1 :(得分:0)

问题在于:

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