Adding google maps to my website

ぃ、小莉子 提交于 2021-02-05 12:30:52

问题


I have a page and im trying to add google map to it but it doesn't appear in the page, it has no errors in the console log but it doesn't appear in my page, here is my code:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD19cqU2rIzBHOPL_t8GhJJ9cmi-HNpULg"></script>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script>
            function initialize() {
              var mapOptions = {
                zoom: 15,
                scrollwheel: false,
                center: new google.maps.LatLng((31.993072, 35.862211))
              };

              var map = new google.maps.Map(document.getElementById('googleMap'),
                  mapOptions);


              var marker = new google.maps.Marker({
                position: map.getCenter(),
                animation:google.maps.Animation.BOUNCE,
                icon: 'img/map-marker.png',
                map: map
              });

            }

            google.maps.event.addDomListener(window, 'load', initialize);
        </script>

回答1:


Do with following

  1. add callback in src <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD19cqU2rIzBHOPL_t8GhJJ9cmi-HNpULg&callback=initialize"></script>
  2. center:new google.maps.LatLng(31.993072, 35.862211) instead of center: new google.maps.LatLng((31.993072, 35.862211)) remove extra round bracket

function initialize() {
  var mapOptions = {
    zoom: 15,
    scrollwheel: false,
    center: new google.maps.LatLng(31.993072, 35.862211)
  };

  var map = new google.maps.Map(document.getElementById('googleMap'),
    mapOptions);


  var marker = new google.maps.Marker({
    position: map.getCenter(),
    animation: google.maps.Animation.BOUNCE,
    //icon: 'img/map-marker.png',
    map: map
  });
}
#googleMap {
  height: 400px;
  width: 100%;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD19cqU2rIzBHOPL_t8GhJJ9cmi-HNpULg&callback=initialize"></script>
<div id="googleMap">

</div>



回答2:


Please note that the particular key for google map only works for the specific domain, so if you are running on localhost, it won't display a map normally.




回答3:


Use iframe to show map in your website:

<iframe  width="600"  height="450"  frameborder="0" style="border:0"  src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY
&q=Space+Needle,Seattle+WA" allowfullscreen>

Google Maps Embed API Link



来源:https://stackoverflow.com/questions/43231277/adding-google-maps-to-my-website

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