Google地图地理编码 - offsetWidth

时间:2015-01-15 15:46:11

标签: javascript c# asp.net google-maps

我在使用Google地图API显示邮政编码时遇到问题。 但是,它会出错:

https://maps.gstatic.com/maps-api-v3/api/js/19/6/main.js

中的行...,列的未处理异常

0x800a138f - JavaScript运行时错误:无法获取未定义或空引用的属性'offsetWidth'

你可以给我一些指导吗?

代码文件:

    public string location = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        using (OleDbConnection conn = new OleDbConnection())
        {
            String connection = System.Configuration.ConfigurationManager.ConnectionStrings["google_string"].ConnectionString;

            conn.ConnectionString = connection;
            conn.Open();

            String sql = "select * from tbl_Post";
            OleDbCommand cmd = new OleDbCommand(sql,conn);
            var rdr = cmd.ExecuteReader();
            rdr.Read();

            if(!string.IsNullOrEmpty(rdr["location"].ToString()))
            {

                location = rdr["location"].ToString();
            }

        }
    }
}

}

asp文件:

    <div>
        <%--map canvas--%>
        <style type="text/css">
            html, body, #map-canvas {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>


        <script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=....">

        </script>

        <script type="text/javascript">
            var geocoder;
            var map;

            function initialize() {
                geocoder = new google.maps.Geocoder();

                var latlng; 
                var mapOptions = {
                    //street level

                    center: new google.maps.LatLng(-34.397, 150.644),
                    zoom: 18,

                }


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

                //load post code address (CALLING FUNCTION)
                codeAddress();
            }


            google.maps.event.addDomListener(window, "load", initialize);

            function codeAddress() {


                geocoder.geocode({ 'address': '<%= location%>' }, 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
                        });
                    } else {
                        alert("Geocode was not succesfull for the following reason" + status);
                    }
                });  
            }
        </script>

    </div>

1 个答案:

答案 0 :(得分:2)

此问题通常是由于地图div未在需要访问它的javascript运行之前呈现。

你几乎就在那里,因为你没有id="map-canvas"的元素。所以给你的div一个id然后它应该按预期工作。

<div id="map-canvas"></div>