setting google maps marker javascript

白昼怎懂夜的黑 提交于 2019-12-11 10:18:29

问题


I embed custom google map to my homepage (under contact) - but how to set the marker on the map and map itself on the right place?

addition to html was:

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="map.js"></script>

and js code is:

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

回答1:


In initialize function you need add var marker variable. Below is simple example to set marker on map when click. Hope this help

function initializeMap() {
    var options = {
        center: new google.maps.LatLng(21.1569, 106.113),
        zoom: 15
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), options);
    
    directionsDisplay = new google.maps.DirectionsRenderer();
    infoWindow = new google.maps.InfoWindow();
    marker = new google.maps.Marker();
    
    
    directionsDisplay.setMap(map);
}

google.maps.event.addListener(map, 'click', function(event) { 
            placeMarker(event.latLng);
        });

function placeMarker(location) {
    
    geocoder.geocode({latLng : location}, function(response, status){
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(response);
            if (response[0]) {
                marker.setMap(map);
                marker.setPosition(location);

                infoWindow.setContent(response[0].formatted_address);
                infoWindow.open(map, marker);
            }
        }
    });
}


来源:https://stackoverflow.com/questions/31577089/setting-google-maps-marker-javascript

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