最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Google map embed url from regular link - Stack Overflow

programmeradmin1浏览0评论

I recently came across a site where you can drag the regular Google map url to the their page and it will automatically embed it via iframe. I read the Google Maps Embed API and it looks like there's no way to do this. I'm not sure if this can be achieved using regex to extract the parameters.

// Sample /@37.3321023,-121.9035969,14z

$(button).click(function() {
   reg-url = $('#inputbox').val();
   convert();
});

function convert() {
    embedid = //get param from reg-url
    $('.wrapper').html("<iframe src='="+embedid+"'>");
}

So basically I want to create a jquery function that will convert regular map url to embed url.

I recently came across a site where you can drag the regular Google map url to the their page and it will automatically embed it via iframe. I read the Google Maps Embed API and it looks like there's no way to do this. I'm not sure if this can be achieved using regex to extract the parameters.

// Sample https://www.google./maps/@37.3321023,-121.9035969,14z

$(button).click(function() {
   reg-url = $('#inputbox').val();
   convert();
});

function convert() {
    embedid = //get param from reg-url
    $('.wrapper').html("<iframe src='https://www.google./maps/embed?pb="+embedid+"'>");
}

So basically I want to create a jquery function that will convert regular map url to embed url.

Share Improve this question edited Feb 7, 2017 at 20:04 Coder 2,2391 gold badge19 silver badges21 bronze badges asked Feb 7, 2017 at 16:47 VianneVianne 5781 gold badge10 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6
function GoogleMapsURLToEmbedURL(GoogleMapsURL)
{
    var coords = /\@([0-9\.\,\-a-zA-Z]*)/.exec(GoogleMapsURL);
    if(coords!=null)
    {
        var coordsArray = coords[1].split(',');
        return "https://www.google./maps/embed?pb=!1m14!1m12!1m3!1d20000!2d"+coordsArray[1]+"!3d"+coordsArray[0]+"!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2suk!4v1486486434098";
    }
}

In your sample:-

https://www.google./maps/@37.3321023,-121.9035969,14z

After the '@', 37.3321023 is one co-ordinate, -121.9035969 is the second, and 14z is the zoom.

I've done the co-ordinates for you, all you'd need to do is write some if's to work out turning the zoom into an integer for the embed (I've set it to always be 20000, which looks to be around the 14th zoom level according to the web interface.

Here is a solution to Converting from a google map url to embeded link for the iframe src attribute .

here i have an iframe that points to a location on google maps , and after 5 seconds , the function "fromLinkToEmbeded" will get the google map url link that is saved on the maplink variable and will change get the coordinates to inject them in the src attribute of the iframe element

<div>
    <iframe id="mapsFrame"
        src="https://www.google./maps/embed?pb=!1m14!1m8!1m3!1d26081.217527432873!2d-0.663236!3d35.2026779!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd7f003333a9b2b5%3A0x2a626a504a41aa51!2sRailway%20station!5e0!3m2!1sen!2sdz!4v1684402795522!5m2!1sen!2sdz" 
        width="450" height="150" style="border:0;" allowfullscreen="" loading="lazy"
        referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>


<script>
 var maplink = "https://www.google./maps/@37.3321023,-121.9035969,14z";

    
    function fromLinkToEmbeded(googleMapsLink) {

        var cordinates = googleMapsLink.split("@")[1];
        var cordX = cordinates.split(',')[0];
        var cordY = cordinates.split(',')[1];
        var zoom = cordinates.split(',')[2].split("z")[0];

        var iframe = document.getElementById('mapsFrame');
        iframe.src = "https://maps.google./maps?q=" + cordX + ", " +
            cordY +
            "&z=" + zoom +
            "&output=embed";

    }
setTimeout(() => {
  fromLinkToEmbeded(maplink);
    }, 5000);
</script>

Here is my solution:

Extract coordinates from a regular link

export const getCoordinatesFromGoogleMapURL = (url: string) => {
  if (!url) {
    return undefined
  }
  const urlParts = url.split('/@')[1]?.split(',')

  if (!(urlParts && urlParts?.length > 1)) {
    return undefined
  }

  const gpsX = parseFloat(urlParts[0])
  const gpsY = parseFloat(urlParts[1])

  if (isNaN(gpsX) || isNaN(gpsY)) {
    return undefined
  }

  return [gpsX, gpsY] as [number, number]
}

Generate embed url from coordinates:

export const generateGoogleMapEmbedUrl = (coordinates: [number, number]) => {
  if (!coordinates) {
    return undefined
  }

  const baseUrl = "https://www.google./maps/embed/v1/streetview"
  const coordinatesString = `${String(coordinates[0])},${String(coordinates[1])}`
  const url = `${baseUrl}?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}&location=${coordinatesString}`

  return url
}

Finally we can put it together:

export function convertToEmbedURL(url: string): string {
  const coordinates = getCoordinatesFromGoogleMapURL(url)
  const embedUrl = generateGoogleMapEmbedUrl(coordinates)

  return embedUrl;
}

You can read the official docs to find out more about params etc: https://developers.google./maps/documentation/embed/embedding-map#streetview_mode

发布评论

评论列表(0)

  1. 暂无评论