在嵌入式谷歌地图中显示我的位置

时间:2014-07-18 08:25:42

标签: javascript google-maps iframe google-maps-api-3 google-maps-markers

我正在使用iframe来显示嵌入式谷歌地图:

<iframe
    id="map_canvas" name="map_canvas"
    src="http://maps.google.com/maps/ms?ie=UTF8&amp;msa=0&amp;msid=205427380680792264646.0004fe643d107ef29299a&amp;output=embed"
    width="100%" height="600px">
</iframe>

我想在这个iframe中添加一个地标标记,它会显示我当前的位置,而无需重定向到Google地图网页。

我尝试使用此脚本实现它,但它不起作用:

你能帮我吗?

<script type="text/javascript">
var watchId;
var map;
var myLocation;
var myLocationMarker = null;

function initialize() {
    var mapOptions = {
        center : new google.maps.LatLng(58, 16),
        zoom : 7,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };

    map = map = new google.maps.Map(document
            .getElementById("map_canvas"), mapOptions);

    if (navigator.geolocation) {
        var optn = {
            enableHighAccuracy : true,
            timeout : Infinity,
            maximumAge : 0
        };
        watchId = navigator.geolocation.watchPosition(showPosition,
                showError, optn);
    } else {
        alert('Geolocation is not supported in your browser');
    }

}

function showPosition(position) {

    if (myLocationMarker != null) {
        myLocationMarker.setMap(null);
    }

    myLocation = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);

    myLocationMarker = new google.maps.Marker({
        position : myLocation,
        map : map
    });

}

function showError(error) {
    switch (error.code) {
    case error.PERMISSION_DENIED:
        alert("User denied the request for Geolocation.");
        break;
    case error.POSITION_UNAVAILABLE:
        alert("Location information is unavailable.");
        break;
    case error.TIMEOUT:
        alert("The request to get user location timed out.");
        break;
    case error.UNKNOWN_ERROR:
        alert("An unknown error occurred.");
        break;
    }
}
</script>

0 个答案:

没有答案