标签:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>谷歌地图测试</title> <style type="text/css"> #gmap{ width: 640px; height: 480px; } </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> </head> <body> <input id="form_lat" type="hidden" name="lat" value="" /> <input id="form_lng" type="hidden" name="lng" value="" /> <input id="form_addr" type="text" name="addr" value="北京天安门" /><input id="form_position" type="button" value="定位" /> <div id="gmap"></div> </body> <script type="text/javascript"> window.onload = function() { document.getElementById("form_position").onclick=function(){ var addr = document.getElementById(‘form_addr‘).value; gmap.setPoint(addr); }; var addr = document.getElementById(‘form_addr‘).value; gmap.init(‘gmap‘, {‘addr‘: addr, ‘mtitle‘: ‘北京‘, ‘mcontent‘: ‘这里是天安门‘}); } var gmap = { // 初始值 map: null, point: null, marker: null, opt: { addr: ‘‘, lat: null, lng: null, mtitle: ‘‘, mcontent: ‘‘, form_lng: ‘form_lng‘, form_lat: ‘form_lat‘ }, init: function(gmapId, option){ // 初始参数 for(var k in option){ this.opt[k] = option[k]; } // 初始地图 var lat = this.opt.lat ? this.opt.lat : 11.530653202560947; var lng = this.opt.lng ? this.opt.lng : 104.90425376000007; this.point = new google.maps.LatLng(lat, lng); this.map = new google.maps.Map(document.getElementById(gmapId), { center: this.point, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }); this.setMarker(); if( this.opt.addr != ‘‘ ){ this.setPoint(this.opt.addr); } }, setMarker: function(){ var self = this; // 添加标记. if( !this.marker ){ this.marker = new google.maps.Marker({ position: this.point, draggable: true, map: this.map, title: "" }); }else{ this.marker.setPosition(this.point); } // Marker添加点击事件 if( this.opt.mtitle != ‘‘ ){ var contentString = ‘<div id="content"><h1>‘+this.opt.mtitle+‘</h1>‘+ ‘<p class="mapStyle">‘+this.opt.mcontent+‘</p></div>‘; var infowindow = new google.maps.InfoWindow({ content: contentString }); google.maps.event.addListener(self.marker, ‘click‘, function () { infowindow.open(self.map, self.marker); }); } // 获取坐标 google.maps.event.addListener(self.marker, "dragend", function() { self.point = self.marker.getPosition(); self.map.setCenter(self.point); var lat = self.point.lat(); var lng = self.point.lng(); document.getElementById(self.opt.form_lng).value = lng; document.getElementById(self.opt.form_lat).value = lat; }); }, setPoint: function(addr){ // 根据地名来获取经纬度 var self = this; var addr = addr ? addr : ‘柬埔寨‘; var geocoder = new google.maps.Geocoder(); geocoder.geocode({‘address‘: addr}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { self.point = results[0].geometry.location; } else { var lat = 11.530653202560947; var lng = 104.90425376000007; self.point = new google.maps.LatLng(self.lat, self.lng); } self.map.setCenter(self.point); self.setMarker(); }); } } </script> </html>
效果如下:
标签:
原文地址:http://my.oschina.net/skq/blog/509241