谷歌地图api在谷歌浏览器扩展程序中不起作用

时间:2012-11-06 05:59:48

标签: javascript jquery google-maps google-maps-api-3 google-chrome-extension

我正在使用JavaScript,HTML,CSS制作Google Chrome扩展程序。为此,我需要读取用户提供的地址的经度和纬度。在测试我的扩展程序时,我一直在低于错误

Error

这是我的js代码

result: {
            data: function (from, to, hrs, mins) {
                fromaddress     = from;
                toaddress   = to;
                hours       = hrs;
                minutes     = mins;

                View.result.readLatLng();
            },

            readLatLng: function () {
                //var addressone = document.getElementById("addressone").value;
                geocoder    = new google.maps.Geocoder();
                geocoder.geocode( { 'address': fromaddress}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    var latitude = results[0].geometry.location.latitude;
                    var longitude = results[0].geometry.location.longitude;
                    console.log('lat: ' + latitude + ', lng: ' + longitude);
                  } else {
                    alert("Geocode was not successful for the following reason: " + status);
                  }
                });
            }
        }

这是我的manifest.json文件

{
  "name": "Name",
  "version": "1.0",
  "manifest_version": 2,
  "background": { 
    "scripts": [
      "js/result.js",
      "js/script.js"
    ] 
  },
  "description": "Desc",
  "browser_action": {
    "default_icon": "images/icon.png",
    "default_title": "Title",
    "default_popup": "html/popup.html"
  },
  "permissions": [ 
    "http://*/",
    "https://maps.google.com/*",
    "https://maps.googleapis.com/*",
    "http://localhost/*",
    "geolocation"
  ],
  "content_security_policy": "script-src 'self' https://maps.googleapis.com https://maps.gstatic.com; object-src 'self'"
}

请帮助我如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

Google Maps API加载程序使用document.write(),显然Chrome扩展程序不允许这样做。见here

  

我在Google Chrome浏览器的扩展程序中使用您的地图。现在我尝试切换   到Chrome扩展程序manifest.v2,发现内容安全策略   需要使用。但是你的代码包含“eval”函数的使用和   document.write加载脚本,因此无法初始化您的地图。

答案 1 :(得分:1)

对于Marcelo的回答,这是的附录,因为我还没有评论,我的编辑被拒绝了。

您可以通过添加"content_security_policy"属性(例如

)更改清单文件中的'unsafe-eval'密钥来规避问题
"content_security_policy": "script-src 'self' 'unsafe-eval' https://; object-src 'self'"

Discussion of Chrome Extension Content Security Policy

正如Marcelo的回答中提到的那样,Google Maps API源代码中的Streetview代码使用了document.write(),这是一种类似eval的构造。 Eval本质上是不安全的,因此Google希望使用他们的Maps API源代码来解决这个问题。

我不确定这可能会影响如何提交Chrome商店的扩展程序。但是,我已成功在本地解压缩扩展程序中使用Google Maps API。

答案 2 :(得分:0)

在构建网络应用时,我也遇到了Google Geocoding API的问题。我可以立即看到您的代码的一个潜在问题是如何获得lat和lng。

请改为尝试:

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();