简体   繁体   English

如何从JQuery ajax请求从Google Api Street View获取图像?

[英]How to get image from Google Api Street View from JQuery ajax request?

I'm using Google API for getting Street View. 我正在使用Google API获取街景视图。

My Code : 我的代码:

$.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);
        }
       });

Where MY_KEY is my Google API key and location will be dynamic as per latitude and longitude for particular place. 其中MY_KEY是我的Google API密钥, location将根据特定位置的经纬度动态变化。 But it always goes in error . 但是它总是会error And if it successfully runs I want it to bind in html img tag. 如果成功运行,我希望它绑定在html img标签中。

Hope this will help and it will work by replacing your parameter: 希望这会有所帮助,并且可以通过替换参数来起作用:

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

but it will display Street view in div instead of img tag. 但它将在div中显示街景视图,而不是img标签。

Google API supplies raw image data. Google API提供原始图像数据。 In order to show it in browser you need to set the image data to some HTML. 为了在浏览器中显示它,您需要将图像数据设置为一些HTML。

There can be lots of approach of doing so. 这样做有很多方法。 Though old you can see this post - https://stackoverflow.com/a/20285053/926943 -- this guy's response is just awesome. 虽然很老,但您可以看到这篇文章-https: //stackoverflow.com/a/20285053/926943-这个家伙的回应真是太棒了。

For your particular problem -- I have used the above post to create a solution. 对于您的特定问题-我已使用以上文章创建了一个解决方案。 Have a look: 看一看:

HTML : HTML

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

JAVASCRIPT : 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 : JSFIDDLE

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM