Google Maps: Can't add marker

流过昼夜 提交于 2019-12-25 06:39:05

问题


Can't get a marker added, probably something very simple but I'm new to this. Thanks.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true"></script>
    <script type="text/javascript">

        function addMarker() {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(-34.397, 150.644),

                title:"Hello World!"
            });
        }


        function initialize() {
            var mapOptions = {
                center: new google.maps.LatLng(-34.397, 150.644),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
        }
        google.maps.event.addDomListener(window, 'load', initialize);

        $(document).ready(function() {
            addMarker();
        })

    </script>

回答1:


Two issues, you need to set the map variable of the marker. Your map variable is local to the initialize function.

  • call the addMarker function from your initialize function (where the map exists), after the map is initialized.

        function addMarker(map) {
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(-34.397, 150.644),
            map:map,
    
            title:"Hello World!"
          });
        }
    
        function initialize() {
          var mapOptions = {
            center: new google.maps.LatLng(-34.397, 150.644),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          var map = new google.maps.Map(document.getElementById("map-canvas"),
          mapOptions);
          addMarker(map);
        }
    

working example




回答2:


You have to set map property in marker constructor or invoke setMap on a new object:

var marker = new google.maps.Marker({
            position: new google.maps.LatLng(-34.397, 150.644),
            map: map,   //make your map object global!
            title:"Hello World!"
        });

or

marker.setMap(map);

https://developers.google.com/maps/documentation/javascript/reference#Marker

EDIT: my comment about making map object global was apparently overlooked, so here it is:

map object is supposed to be global, not only for the sake of this solution, but you are going to need it in multiple functions in your script



来源:https://stackoverflow.com/questions/15413136/google-maps-cant-add-marker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!