为什么它不在地图上显示标记?

时间:2017-10-20 09:23:48

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

我尝试了不同的代码,仍然不知道为什么我的标记不显示。 我一直在搜索和阅读谷歌开发人员的文档,并尝试了他们解释的所有方式,没有。还试着看看是否有任何sintax错误(并且它必须是......)但是因为我是新手,所以看起来没有错误。

所以,有人知道我的代码有什么问题吗?

<?php

get_header(); ?>

<div id="map"></div><!-- #map-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAp9iQ2oC3PEvy20_6aDpAPGLT8sFDqAjI&libraries=geometry,places&signed_in=true"></script>
<script type="text/javascript">
    google.maps.event.addDomListener( window, 'load', gmaps_results_initialize );

    function gmaps_results_initialize() {
        var map = new google.maps.Map( document.getElementById( 'map' ), {
        zoom:           3,
        center:         new google.maps.LatLng( 28.291564, 16.62913 ),
        mapTypeControl: true,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
          position: google.maps.ControlPosition.RIGHT_BOTTOM
       },
       zoomControl: true,
       zoomControlOptions: {
          position: google.maps.ControlPosition.LEFT_CENTER
       },
       scaleControl: true,
       streetViewControl: true,
       streetViewControlOptions: {
          position: google.maps.ControlPosition.LEFT_BOTTOM
       },
       fullscreenControl: true
       });
       var infoWindow = new google.maps.InfoWindow({map: map});

       // Try HTML5 geolocation.
          if (navigator.geolocation) {
             navigator.geolocation.getCurrentPosition(function(position) {
             var pos = {
             lat: position.coords.latitude,
             lng: position.coords.longitude
             };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            map.setCenter(pos);
            }, function() {
               handleLocationError(true, infoWindow, map.getCenter());
            });
         } else {
           // Browser doesn't support Geolocation
           handleLocationError(false, infoWindow, map.getCenter());
           }

        };      
</script>
<script>
       var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
       var mapOptions = {}
       var map = new google.maps.Map(document.getElementById("map"), mapOptions);
       var marker = new google.maps.Marker({});

      // To add the marker to the map, call setMap();
       marker.setMap(map);
    </script>
<script src="/geo.js"></script>
<?php
get_sidebar();
get_footer();

1 个答案:

答案 0 :(得分:0)

我认为是因为你正在为地图创建两个对象。 使地图对象成为常量。不要重新初始化它。

您已在函数外部添加了标记,并使其在初始化方法之前执行,该方法将在google maps脚本加载时调用,因此未添加标记因为map未初始化。创建单独的方法TestMarker并从初始化调用它。

function addMarker(location) {
    marker = new google.maps.Marker({
        position: location,
        map: map
    });
}

 function TestMarker() {
       CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
       addMarker(CentralPark);
}

在初始化函数中调用TestMarker

注意:map在这里是常量。