问题
I have been using the google maps API to create a custom google map entirely based on my own images, and have found ways to make markers or HTML div elements zoom in on specific locations. However, I am wondering is there any way to create a URL link that links directly to a location and zoom level on the map?
The idea being that if one were to click on a different link (from outside the site) one would enter the site straight at a specified location, instead of the default location.
I know this is already possible with links taken from the original google maps (as opposed to custom versions), is it possible with the API?
Thanks a lot
回答1:
With the current API, no. But you can use the URLON library to easily build and parse an object in the URL - which you can use to set your map options.
Essentially you use the URLON.parse()
method to parse your hash in the URL. Then use the attributes in the generated object to set your google.maps.MapOptions
on load. Putting it together will yield:
//remove the # from the hash string, as URLON starts parsing from the underscore
urlMapOptions = URLON.parse(hash.substr(1, hash.length));
var mapOptions = {
zoom: (urlMapOptions.zoom) ? parseFloat(urlMapOptions.zoom) : 8,
center: (urlMapOptions.lat && urlMapOptions.long) ? new google.maps.LatLng(parseFloat(urlMapOptions.lat), parseFloat(urlMapOptions.long)) : new google.maps.LatLng(43.7, -79.4),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
Here is the link to the map, which defaults to Toronto and a zoom level of 8: http://svignara.github.io/loadgmapwithlink.html
And here is the link to the map, which loads the center to Chicago at a zoom level of 12: http://svignara.github.io/loadgmapwithlink.html#_lat=41.8819&long=-87.6278&zoom=12
Link to github repo: html, JS.
来源:https://stackoverflow.com/questions/18702863/creating-a-url-that-links-to-a-specific-location-in-a-custom-google-map