使用url将变量传递到嵌入式Google Map

时间:2017-11-15 21:39:25

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

首先,我是javascript和google maps API的新手。我设法在页面上获得了一个嵌入式谷歌地图,其中一个可拖动的标记显示更新的lat和long。我正在努力解决的问题是使用URL中包含的变量设置初始标记位置,例如:

http://example.com?q=12.989802,-80.2487



<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<style> html, body, #map_canvas {
    margin: 0;
    padding: 0;
    height: 100%
}
</style>

<body>Lat:
    <input id="lat" name="lat" val="40.713956" />Long:
    <input id="long" name="long" val="74.006653" />
    <br />
    <br />
    <div id="map_canvas" style="width: 100%; height: 90%;"></div>
</body>

<script>


    var map;
    function initialize() {
    
    var urlParams = /\?q=([^,]+),([^,]+)/.exec(window.location.search), 
            var myLatlng;

    if (urlParams) {
        var myLatlng = new google.maps.LatLng(parseFloat(urlParams[1]), parseFloat(urlParams[2]));
    } else {
        return;
    }
    
        var myOptions = {
            zoom: 8,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            position: myLatlng,
            map: map,
            title: "Your location"
        });

        google.maps.event.addListener(marker, 'dragend', function (event) {


            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("long").value = event.latLng.lng();
        });
    }
    google.maps.event.addDomListener(window, "load", initialize());

</script>
&#13;
&#13;
&#13;

0 个答案:

没有答案