MrBubbles MrBubbles - 2 months ago 6
HTML Question

Write Query String into HTML Document

I have a challenge of trying to embed the Google StreetView for a specific location in on a web page. Normally, I would just use Google's iFrame embed but the platform on which the page is hosted doesn't allow iFrames.

So if I can't use an iFrame, I have to go the traditional way of using a pure HTML document and Google's true StreetView embed approach. That's fine except that I want to parameterize the URL so that the user can pass in a query string to tell the StreetView what location to display.

http://my.site.com/streetview.html&y=37.869260&x=-122.254811


Google's StreetView embed document gives me a great example of dropping StreetView right into an HTML Document.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Street View</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#street-view {
height: 100%;
}
</style>
</head>
<body>
<div id="street-view"></div>
<script>
var panorama;
function initialize() {
panorama = new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
position: {lat: 37.869260, lng: -122.254811},
pov: {heading: 165, pitch: 0},
zoom: 1
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=[YourAPIKey]&callback=initialize">
</script>
</body>
</html>


I'm trying to modify the Script section to write the values passed to the 'y' and 'x' query strings into the StreetView element's 'lat' and 'lng' variables so that the StreetView will always be at whatever location I pass in as the y and x query strings in the URL.

<script>
var panorama;
function initialize() {
panorama = new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
position: {lat: 37.869260, lng: -122.254811},
pov: {heading: 165, pitch: 0},
zoom: 1
});
}
</script>

Answer

If I got your question right, you want to get the lattitude and longitude values from Query string.

First, you need to get query params, add this function-

    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

Then modify your script as follows -

<script>
  var panorama;
  var latt,longg;
  latt = parseInt(getParameterByName('y'));
  longg = parseInt(getParameterByName('x')); 
  function initialize() {
    panorama = new google.maps.StreetViewPanorama(
        document.getElementById('street-view'),
        {
          position: {lat: latt, lng: longg},
          pov: {heading: 165, pitch: 0},
          zoom: 1
        });
  }
</script>

Let me know If I misunderstood your question.