【问题标题】:How to get image from Google Api Street View from JQuery ajax request?如何通过 JQuery ajax 请求从 Google Api Street View 获取图像?
【发布时间】:2016-04-20 05:59:48
【问题描述】:

我正在使用 Google API 获取街景。

我的代码:

$.ajax({
        url: 'https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988&heading=151.78&pitch=-0.76&key=MY_KEY',
        contentType: "image/jpeg",
        type: 'GET',
        cache: false,
        success: function(data) {
           console.log('got data', data);
        },
        error: function(error) {
           console.log('Error', error);
        }
       });

MY_KEY 是我的 Google API 密钥,location 将根据特定地点的纬度和经度动态变化。 但它总是进入error。 如果它成功运行,我希望它绑定在 html img 标签中。

【问题讨论】:

    标签: javascript jquery html ajax google-api


    【解决方案1】:

    Google API 提供原始图像数据。为了在浏览器中显示它,您需要将图像数据设置为一些 HTML。

    有很多方法可以做到这一点。虽然老了你可以看到这个帖子 - https://stackoverflow.com/a/20285053/926943 - 这家伙的反应真是太棒了。

    针对您的特定问题——我已使用上述帖子来创建解决方案。看看:

    HTML

    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
    <div id="map_div"></div>
    

    JAVASCRIPT

    var imageUrl = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location=23.7610974,90.3720526&heading=310";
    convertFunction(imageUrl, function(base64Img){
            var img = "<img src='"+base64Img+"'>";
        $('#map_div').html(img);
    });
    
    function convertFunction (url, callback){
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function() {
            var reader  = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            }
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.send();
    }
    

    JSFIDDLE

    https://jsfiddle.net/nagbaba/bonLzt67/

    【讨论】:

      【解决方案2】:

      希望这会有所帮助,并且可以通过替换您的参数来工作:

      https://developers.google.com/maps/documentation/javascript/examples/streetview-embed

      但它会在 div 而不是 img 标签中显示街景。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-24
        • 1970-01-01
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        相关资源
        最近更新 更多