简体   繁体   中英

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

I'm using Google API for getting Street View.

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. But it always goes in error . And if it successfully runs I want it to bind in html img tag.

Hope this will help and it will work by replacing your parameter:

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

but it will display Street view in div instead of img tag.

Google API supplies raw image data. In order to show it in browser you need to set the image data to some 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.

For your particular problem -- I have used the above post to create a solution. Have a look:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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