代码我在google map api demo的基础上小小的修改了下:
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
- <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
- <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
- <script type="text/javascript">
- var geocoder;
- var map;
- function initialize() {
- geocoder = new google.maps.Geocoder();
- var latlng = new google.maps.LatLng(31.23, 121.47);
- var myOptions = {
- zoom: 12,
- center: latlng,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- }
- map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
- }
- function codeAddress() {
- var address = document.getElementById("address").value;
- geocoder.geocode( { 'address': address}, function(results, status) {
- if (status == google.maps.GeocoderStatus.OK) {
- console.log(results[0].geometry.location)
- map.setCenter(results[0].geometry.location);
- this.marker = new google.maps.Marker({
- title:address,
- map: map,
- position: results[0].geometry.location
- });
- var infowindow = new google.maps.InfoWindow({
- content: '<strong>'+address+'</strong><br/>'+'纬度: '+results[0].geometry.location.Da+'<br/>经度: '+results[0].geometry.location.Ea
- });
- infowindow.open(map,marker);
- } else {
- alert("Geocode was not successful for the following reason: " + status);
- }
- });
- }
- </script>
- </head>
- <body onload="initialize()">
- <div>
- <input id="address" type="textbox" value="上海市">
- <input type="button" value="地址解析" onclick="codeAddress()">
- </div>
- <div id="map_canvas" style="height:90%;top:30px"></div>
- </body>
- </html>