在地图上获取所提供地址的位置的代码

时间:2011-07-12 06:11:56

标签: asp.net

我是这个平台的新手,如果有人可以建议我使用代码片段来查看我的应用是否需要找到Google地图上提供的地址。

1 个答案:

答案 0 :(得分:0)

Javascript:

var geocoder;
var map;

function initialize() {
    geocoder = new google.maps.Geocoder();
    var latitide = 50.445516;
    var longitude = 30.452188;
    var addressHiddenField = document.getElementById("<%= AddressCoordinates.ClientID %>");

    if (addressHiddenField.value.length > 0) {
        latitide = parseFloat(addressHiddenField.value.split(";")[0]);
        longitude = parseFloat(addressHiddenField.value.split(";")[1]);
    }

    var latlng = new google.maps.LatLng(latitide, longitude);
    var myOptions = {
        zoom: 15,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

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

function codeAddress() {
    var addressHiddenField = document.getElementById("<%= AddressCoordinates.ClientID %>");
    var address = document.getElementById("<%= AddressTextBox.ClientID %>").value;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            addressHiddenField.value = results[0].geometry.location.lat() + ";" + results[0].geometry.location.lng();
        }
        else {
            addressHiddenField.value = "";
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

标记:

<body onload="initialize()">
<form id="form1" runat="server">
<div id="map_canvas" style="width: 100%; height: 480px;">
</div>
<div>
    <asp:TextBox runat="server" ID="AddressTextBox" />
    <asp:Button runat="server" ID="GetAddressCoordinatesButton" OnClientClick="codeAddress()"
        Text="Search Address" />
    <hr />
    <asp:HiddenField runat="server" ID="AddressCoordinates" />
</div>
</form>