如何在MVC中显示谷歌地图?

时间:2017-02-14 08:48:24

标签: asp.net-mvc google-maps

我想在我的网站上显示谷歌地图,我的代码在下面,但在浏览器中加载我的页面后出现此错误:

Oops! Something went wrong.
This page didn't load Google Maps correctly. See the JavaScript console for  
technical details.

我在Chrome中查看了它,发现了这个:

Google Maps API error: MissingKeyMapError 
https://developers.google.com/maps/documentation/javascript/error-
messages#missing-key-map-error

什么是MissingKeyMap?

我的代码:

标题标记中的

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
<link href="~/Content/Site.css" rel="stylesheet" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?
 sensor=false"></script>


<script type="text/javascript">

    function initialize() {

        var canvas = $("#map_canvas");

        var latitude = 35.78334;
        var longitude = 51.42511;

        var latlng = new google.maps.LatLng(latitude, longitude);
        var options = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(canvas[0], options);

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(latitude, longitude),
            map: map
        });
    }

    $(function () {
        initialize();
    });

  </script>

在我看来:

<div style="width: 100%; height: 100%">
    <div id="map_canvas" style="width:100%; height:100%; margin-left:   100px"></div>
 </div>

2 个答案:

答案 0 :(得分:3)

在Google地图的js代码中,您可能会发现类似https://maps.googleapis.com/maps/api/js?key=YOURKEYHERE&callback=initMap

的内容

YOURKEYHERE替换为您自己的Google API密钥。转到this link获取您自己的密钥并将其替换为YOURKEYHERE,它应该可以正常工作。

答案 1 :(得分:0)

这一切都在这里解释。

https://developers.google.com/maps/documentation/javascript/get-api-key

您需要在javascript的网址中提供api-key

 <script async defer src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&callback=initMap"  type="text/javascript"></script>