Google Map を表示してマーカーを追加するJavascript
このページでの使用例
<script src="http://maps.google.com/maps?file=api&v=2&key=[Your API Key]" type="text/javascript"></script>
<script type="text/javascript" src="simple_gmap.js"></script>
<script type="text/javascript">
var simple_gmap = new SimpleGMap("gmap");
simple_gmap.addMarker(35.658517,139.701334,"渋谷駅");
simple_gmap.addMarker(35.690921,139.700258,"新宿駅");
simple_gmap.addMarker(35.681099,139.767084,"東京駅");
</script>
<style type="text/css">
#gmap
{
width: 898px;
height: 448px;
border: 1px solid #ccc;
background: #eee;
}
</style>
...
<div id="gmap">読み込んでいます...</div>
コード
SimpleGMap = function(id, lat, lng, zoom)
{
if(!id) return; else this.id = id;
(!!lat)?this.lat=lat:this.lat=35.687168;
(!!lng)?this.lng=lng:this.lng=139.757412;
(!!zoom)?this.zoom=zoom:this.zoom=10;
this.map;
this.mapControl = new GLargeMapControl();
this.mapScale = true;
this.mapType = true;
this.mapOverview = true;
this.markers = [];
this.onLoad(this, "createMap");
}
//
// public function
//
SimpleGMap.prototype.addMarker = function(lat, lng, label)
{
var obj = { lat: lat,
lng: lng,
label: label
}
this.markers.push(obj);
}
SimpleGMap.prototype.addMapControl = function(type)
{
if(type=="L") this.mapControl = new GLargeMapControl();
else if(type=="S") this.mapControl = new GSmallMapControl();
else this.mapControl = false;
}
SimpleGMap.prototype.addScale = function(b)
{
this.mapScale = b;
}
SimpleGMap.prototype.addType = function(b)
{
this.mapType = b;
}
SimpleGMap.prototype.addOverview = function(b)
{
this.mapOverview = b;
}
//
// private function
//
SimpleGMap.prototype.onLoad = function(scope, func)
{
if(window.addEventListener) window.addEventListener('load', function(e){ scope[func](e); }, false);
else if(window.attachEvent) window.attachEvent('onload', function(e){ scope[func](e); });
}
SimpleGMap.prototype.createMap = function()
{
if(GBrowserIsCompatible())
{
this.map = new GMap2(document.getElementById(this.id));
if(this.mapControl) this.map.addControl(this.mapControl);
if(this.mapScale) this.map.addControl(new GScaleControl());
if(this.mapType) this.map.addControl(new GMapTypeControl());
if(this.mapOverview) this.map.addControl(new GOverviewMapControl());
this.map.setCenter(new GLatLng(this.lat, this.lng), this.zoom);
}
var len = this.markers.length;
var bounds = new GLatLngBounds();
for(var i=0; i<len; i++)
{
var m = this.markers[i];
var marker = this.createMarker(m.lat, m.lng, m.label);
this.map.addOverlay(marker);
bounds.extend(new GLatLng(m.lat, m.lng));
}
if(len>1) this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds));
}
SimpleGMap.prototype.createMarker = function(lat, lng, label)
{
var marker = new GMarker(new GLatLng(lat, lng));
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(label);
});
return marker;
}