I have an html page with google maps in one of the divs called map.
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
Now I want to have the same google maps in multiple webpages. How do I reference this div in other pages.
For e.g.
I have another html file like this
<html><head></head>
<body><div><!--How do I get the map here--></div>
</body></html>
Is it posible using Jquery?
---edit----
So I have a script called myscript.js which has a
jQuery(document).ready(function(){
which in turn has a
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
So how do I load this script anywhere else?
2 Answers 2
You won't reference this div. Map is generated on the fly when page is loaded.
If you thought about using $('#element').load('map.html #map) - it will stripe all the scripts from loaded content, so generation scripts won't be available to run.
Since it's supposed to be the same map try use jQuery.getScript()?
// gmaps.js
function generateMap() {
//your custom logic
}
// html file
<html><head></head>
<body><div id="gmap"></div>
<script>
$.getScript('gmaps.js', function() {
// Call custom function defined in script
generateMap();
});
</script>
</body></html>
You might also look at examples here on stackoverflow of using jQuery.getScript() and google maps:
- jquery: how can i load the Google Maps API via ajax?
http://lostmonocle.com/post/88217865/jquery-getscript-and-the-google-maps-api
EDIT - updated example
// map.js
function generateMap()
{
map = new GMap2(document.getElementById("div_map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var latLong = new GLatLng(parseFloat(52.2322549), parseFloat(21.0387957));
var marker = new GMarker(latLong, {draggable : false});
map.addOverlay(marker);
map.setCenter(latLong, 15);
}
// map.html - ! CHANGE API KEY !
<html>
<head>
<title>Google Map sample</title>
<script type="text/javascript" src="js/jquery-1.7.1-min.js"></script>
<script src="http://maps.google.com/maps?file=api&v=2&key=PUT_YOUR_KEY_HERE&sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="div_map" style="width:500px;height:400px;background-color:red;"></div>
<script type="text/javascript">
$.getScript('map.js', function() {
generateMap();
});
</script>
</body>
</html>
1 Comment
Presuming that you're not looking to actually duplicate the map instance itself on other pages, I would suggest creating a standalone page that you can then reference via an <iframe>. You could try via jQuery, but the map will likely break.