简体   繁体   中英

How to make Google Maps detect location of a passed Google Maps URL

Is there any way to put the longitude and latitude from a passed URL into a marker. So essentially a user would copy and paste the 'Share' URL from Google maps.

EG Places: https://www.google.co.nz/maps/place/The+White+House/@38.8976763,-77.0387238,17z/data=!3m1!4b1!4m5!3m4!1s0x89b7b7bcdecbb1df:0x715969d86d0b76bf!8m2!3d38.8976763!4d-77.0365298?hl=en

or Direct Location: https://www.google.co.nz/maps/place/38%C2%B054'53.8%22N+77%C2%B006'01.6%22W/@38.914936,-77.102638,17z/data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d38.914936!4d-77.100444?hl=en

I would like the initialisation code create a marker at that shared URL location.

So far from other question's I've seen the use of GeoCode API but I'm not sure how the example URL's above can be parsed and the data extracted in JS. Any examples of Ajax calls to API or something like this being done would be appreciated.

The URLs contain the latitude and longitude, so you can extract them easily. Calling putMarkerAtURLCoordinates(SHARED_URL) will place a marker at the coordinates of the url assuming your google maps instance is called "map".

function putMarkerAtURLCoordinates(url){
    //get the latlng object from url
    var myLatLng = getLatLngFromURL(url)
    //create the marker and assign it to the map
    var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Marker title here'
    });
}

function getLatLngFromURL(url){
    //decode url incase its urlencoded
    url = decodeURIComponent(url)
    //find index of @ character
    var atindex = url.indexOf("@")
    //cut off the part before the @ and split the rest up by the comma separator
    var urlparts = url.slice(atindex+1).split(",")
    //parse the values as floats
    var lat = parseFloat(urlparts[0])
    var lng = parseFloat(urlparts[1])
    //return as object
    return {lat:lat,lng:lng}
}

This isn't a stable solution though... If google changes their URL scheme this won't work anymore.

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