简体   繁体   中英

How do I add Google Maps on my site?

I have a form and I want to add a "select location" option.

How can I do this, and how can I place a pin as the selected location?

You may want to consider using the Google Maps API , as davek already suggested .

The following example may help you getting started. All you would need to do is to change the JavaScript variable userLocation with the location chosen by your users from the drop-down field you mention.

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps API Demo</title> 
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false"
            type="text/javascript"></script> 
  </head> 
  <body onunload="GUnload()"> 

    <div id="map_canvas" style="width: 400px; height: 300px"></div> 

    <script type="text/javascript"> 

    var userLocation = 'London, UK';

    if (GBrowserIsCompatible()) {
       var geocoder = new GClientGeocoder();
       geocoder.getLocations(userLocation, function (locations) {         
          if (locations.Placemark)
          {
             var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
             var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
             var east  = locations.Placemark[0].ExtendedData.LatLonBox.east;
             var west  = locations.Placemark[0].ExtendedData.LatLonBox.west;

             var bounds = new GLatLngBounds(new GLatLng(south, west), 
                                            new GLatLng(north, east));

             var map = new GMap2(document.getElementById("map_canvas"));

             map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
             map.addOverlay(new GMarker(bounds.getCenter()));
          }
       });
    }
    </script> 
  </body> 
</html>

The above example would render a map like the one below:

根据所选位置渲染谷歌地图

The map will not show if the Google Client-side Geocoder cannot retreive the coordinates from the address.

Check out the Google Maps API . There's lots of information there and several examples:without knowing more about your environment/requirements it is difficult to be more specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM