使用纬度和经度在谷歌地图上定位

Using latitude and longitude to pin point a location in google maps

本文关键字:谷歌地图 定位 经度 纬度      更新时间:2023-09-26

我写了一个脚本来添加地图到我的网站。内容如下:

<script>
        function initialize() {
            var mapCanvas = document.getElementById('map');
            var mapOptions = {
                center: new google.maps.LatLng(12.9583182, 77.6398512),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(mapCanvas, mapOptions)
        }
        google.maps.event.addDomListener(window, 'load', initialize);
        </script>  

HTML code:

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

css:

 #map{
    width: 500px;
    height: 400px;
}  

我添加了这个代码来指向一个位置:

var map = new google.maps.Map(document.getElementById("map"), mapOptions);
            //give latitude and long
        var myLatlng = new google.maps.LatLng("12.9583182", "77.6398512");
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: "Bangalore" 
        });   

但是当我使用那个代码时,我页面上的map消失了。我怎样才能让它工作呢?

你在同一个div上创建了两次map,这就是为什么它会发生,只需更改代码如下:

function initialize() {
        var mapCanvas = document.getElementById('map');
        var mapOptions = {
            center: new google.maps.LatLng(12.9583182, 77.6398512),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        var myLatlng = new google.maps.LatLng("12.9583182", "77.6398512");
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: "Bangalore" 
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

不需要添加var map = new google.maps.Map(mapCanvas, mapOptions); 第二次