使用mvc5在cshtml中编写div元素id

时间:2017-03-08 07:45:44

标签: javascript asp.net-mvc

我尝试在我的视图中显示谷歌地图。这是我的代码:

$(document).ready(function () {
    Initialize();
    function Initialize() {
        google.maps.visualRefresh = true;
        var Tunisie = new google.maps.LatLng(36.81881, 10.16596);
        var mapOptions = {
            zoom: 8,
            center: Tunisie,
            mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        var myLatlng = new google.maps.LatLng(36.81881, 10.16596);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Tate Gallery'
        });
        marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }
});

目前,此javascript位于索引视图中。我想在id为map_canvas的div元素中应用此javascript。我在这个cshtml中使用id为map_canvas的div元素,但它没有显示任何内容......

我在哪里可以使用div元素?

1 个答案:

答案 0 :(得分:0)

您需要替换:

<script src="maps.google.com/maps/api/js?sensor=true"; type="text/javascript"></script>

使用:

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

编辑:

这是我在测试项目中的确切代码:

Index.cshtml:

<style>
#map_canvas{
        margin-top: 50px;
        height: 250px;
    }
</style>

@section Scripts{
<script src="http://maps.googleapis.com/maps/api/js?sensor=true" ; type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        Initialize();
        function Initialize() {
            google.maps.visualRefresh = true;
            var Tunisie = new google.maps.LatLng(36.81881, 10.16596);
            var mapOptions = {
                zoom: 8,
                center: Tunisie,
                mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            var myLatlng = new google.maps.LatLng(36.81881, 10.16596);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: 'Tate Gallery'
            });
            marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
            });
        }
    });
</script>
}