使用jQuery Mobile 1.4.2点击listview后加载Google Map

时间:2014-04-26 00:12:32

标签: google-maps listview jquery-mobile

我试图在单页JQM项目中显示Google地图。

需要在listview clik之后显示地图以使用地图加载新页面。

型号:

public class address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

脚本:

// listview events
$(".address").on("click", function ()
{
    var addressId = this.id;
    var addressPage = "#address";

    addressRequest(addressPage, addressId);
});

function addressRequest(page, addressId)
{
    var $page = $(page);

    $.ajax({
        type: "GET",
        url: urlBase + "/GetAddress",
        crossDomain: false,
        beforeSend: function () { $.mobile.loading('show') },
        complete: function () { $.mobile.loading('hide') },
        data: { addressId: addressId },
        dataType: 'json',
        success: function (address)
        {
            addressBuild(page, address);
            addressLoad(page);
        },
        error: function () {
            console.log("loadList error!");
        }
    });
}

function addressBuild(page, address)
{
    var $page = $(page);

    $(".ui-content", $page).append('<p>' + address.Name + '</p>');

    var centerLatLng = new google.maps.LatLng(address.Latitude, address.Longitude);

    addressLoadMap(centerLatLng);
}

function addressLoad(page)
{
    var $page = $(page);

    $.mobile.pageContainer.pagecontainer("change", $page, { transition: "slide" });
}

function addressLoadMap(latlng)
{
    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
}

HTML:

地址页面列表视图:

    <!-- page addresses list -->
    <div data-role="page" id="addresses">

        <div data-role="header" data-position="fixed"><h1>mobile</h1></div>

        <div class="ui-content" role="main">
           <li><a href="" id="1" class="address">Company A<span class="ui-li-count">distance: 2.0 km</span></a></li>
        </div>
            <li><a href="" id="2" class="address">Company B<span class="ui-li-count">distance: 3.0 km</span></a></li>
        </div>
    </div>

地址页面:

    <style>
        #map-canvas {
            width: 100%;
            height: 100%;
            padding: 0;
        }
    </style>

    <!-- page address -->
    <div data-role="page" id="address">

        <div data-role="header" data-position="fixed"><h1>mobile</h1></div>

        <div class="ui-content" role="main">
            <div id="map-canvas"></div>
        </div>

    </div>

我收到以下错误:

Uncaught TypeError: Cannot read property 'offsetWidth' of null

知道发生了什么事吗?

感谢。

1 个答案:

答案 0 :(得分:1)

我发现了问题,我正在加载地图很快,容器尚未加载。

我只能在显示页面时加载地图:

$(document).on("pageshow", "#address", function ()
{
    addressLoadMap();
});