如何将Google Map API用于Web? [英] How to use Google Map API for Web?

查看:91
本文介绍了如何将Google Map API用于Web?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的谷歌地图API,所以我不知道如何使用它。



所以我想要一些指导或参考链接来处理它。 / p>

需要:

我在地图上有一个位置,我想显示一些自定义标记,例如对于学校,医院等。

我有学校,医院等标签。



当我点击学校然后在2公里(KM下拉列表)显示我所在学校周围的所有学校,当您悬停或点击特定学校时,它会自动告诉我们距离我所在地点有多远。

图像像这样:





我已阅读google地图参考链接:



解决方案

我为您创建了一个工作示例。要获取当前位置,请按获取我的位置,它将使用HTML5地理定位API获取您的坐标并 google.maps.Geocoder 将这些坐标转换为地址。按在半径显示位置显示地图上的半径,并仅显示半径内的标记。此函数使用各种Google地图API调用来绘制半径( google.maps.Circle ),标记( google.maps.Marker Geocoder 以及 google.maps.geometry.spherical.computeDistanceBetween 它以米为单位计算两个位置之间的距离。该示例适用于虚拟位置数据 all_locations (这些仅仅是纽约第二街附近的示例标记),您可以用您的数据替换它们。当你点击一个标记时,它将显示距离输入位置的距离。要查看示例位置,请输入Second Steet,New York作为地址。 (获取我的位置不会在代码片段iframe中工作,您必须在您的本地主机上尝试它)

var map = null; var radius_circle = null; var markers_on_map = []; var geocoder = null; var infowindow = null; // all_locations只是一个示例,你可能会加载数据库var all_locations = [{type:restaurant,name:Restaurant 1,lat:40.723080,lng:-73.984340},{type:school,名称:School 1,lat:40.724705,lng:-73.986611},{type:school,name:School 2,lat:40.724165,lng:-73.983883},{type:restaurant Restaurant 2,lat:40.721819,lng:-73.991358},{type:school,name:School 3,lat:40.732056,lng:-73.998683}]; (文档).ready(函数(){var latlng = new google.maps.LatLng(40.723080,-73.984340); //您可以使用任何位置作为地图启动的中心var myOptions = { zoom:1,center:latlng,mapTypeControl:true,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU},navigationControl:true,mapTypeId:google.maps.MapTypeId.ROADMAP}; map = new google.maps.Map( document.getElementById(map_canvas),myOptions); geocoder = new google.maps.Geocoder(); google.maps.event.addListener(map,'click',function(){if(infowindow){infowindow.setMap null); infowindow = null;}}); $('#location_type')。change(function(){if(radius_circle)showCloseLocations();});});函数showCloseLocations(){var i; var radius_km = $('#radius_km')。val(); var address = $('#address')。val(); var location_type = $('#location_type')。val(); //如果(radius_circle){radius_circle.setMap(null); //显示新的半径和标记, radius_circle = null; } for(i = 0; i< markers_on_map.length; i ++){if(markers_on_map [i]){markers_on_map [i] .setMap(null); markers_on_map [i] = null; }} if(geocoder){geocoder.geocode({'address':address},function(results,status){if(status == google.maps.GeocoderStatus.OK){if(status!= google.maps.GeocoderStatus .ZERO_RESULTS){var address_lat_lng = results [0] .geometry.location; radius_circle = new google.maps.Circle({center:address_lat_lng,radius:radius_km * 1000,clickable:false,map:map}); if(radius_circle) map.fitBounds(radius_circle.getBounds()); for(var j = 0; j

< script src =https:// ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script><script type =text / javascriptsrc =http://www.google。 com / jsapi>< / script>< script type =text / javascript> google.load(maps,3,{other_params:sensor = false& libraries = geometry}); < / script>< body style =margin:0px; padding:0px; > < input id =addressvalue =Second Steet,New Yorkplaceholder =Input Address/> < select id =radius_km> < option value = 1> 1km< / option> < option value = 2> 2km< / option> < option value = 5> 5km< / option> < option value = 30> 30km< / option> < /选择> < select id =location_type> < option value =restaurant> Restaurant< / option> < option value =school>学校< / option> < /选择> < button onClick =getMyAdress()>获取我的位置< / button> < button onClick =showCloseLocations()>显示半径中的位置< / button> < div id =map_canvasstyle =width:500px; height:300px;>< / body>< / html>


I am new For Google Map API so i don't know how to use it.

So i want some guidance or reference link to work on it.

Need :

I have a location on map and i want to show some custom markers such as For schools, hospitals etc.

i have tabs for Schools, Hospitals etc.

when i click on schools then in 2km(dropdown for KM) show all schools around my location and when hover or click on particular school it automatically tells us how much distance from my location.

Image Like this :

I have read google map reference link :

https://developers.google.com/maps/web/

But i am very confused. So please give some advise and useful link.

Another Image :

解决方案

I have created a working example for you. To get your current location press Get My Location and it would use HTML5 geolocation API to get your coordinates and google.maps.Geocoder to translate those coordinates into an address. Press Show Locations In Radius to show radius on map and also show only markers which are within the radius. This function uses various google maps API calls to draw radius (google.maps.Circle), markers (google.maps.Marker - read API if you want to know more about custom styling), Geocoder and also google.maps.geometry.spherical.computeDistanceBetween which computes distance between two locations in meters. The example works with dummy location data all_locations (those are just example markers around New York's Second Street) which you would replace with your data. When you click on a marker, it would display distance in meters from the input location. To see the example location, input "Second Steet, New York" as address. (Get My Location won't work inside the snippet iframe, you have to try it on your localhost)

var map = null;
  var radius_circle = null;
  var markers_on_map = [];
  var geocoder = null;
  var infowindow = null;
  
  //all_locations is just a sample, you will probably load those from database
  var all_locations = [
	  {type: "restaurant", name: "Restaurant 1", lat: 40.723080, lng: -73.984340},
	  {type: "school", name: "School 1", lat: 40.724705, lng: -73.986611},
	  {type: "school", name: "School 2", lat: 40.724165, lng: -73.983883},
	  {type: "restaurant", name: "Restaurant 2", lat: 40.721819, lng: -73.991358},
	  {type: "school", name: "School 3", lat: 40.732056, lng: -73.998683}
  ];

  //initialize map on document ready
  $(document).ready(function(){
      var latlng = new google.maps.LatLng(40.723080, -73.984340); //you can use any location as center on map startup
      var myOptions = {
        zoom: 1,
        center: latlng,
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	  geocoder = new google.maps.Geocoder();
      google.maps.event.addListener(map, 'click', function(){
           if(infowindow){
             infowindow.setMap(null);
             infowindow = null;
           }
      });
      $('#location_type').change(function(){
         if(radius_circle) showCloseLocations();
      });
  });
  
  function showCloseLocations() {
  	var i;
  	var radius_km = $('#radius_km').val();
  	var address = $('#address').val();
    var location_type = $('#location_type').val();

  	//remove all radii and markers from map before displaying new ones
  	if (radius_circle) {
  		radius_circle.setMap(null);
  		radius_circle = null;
  	}
  	for (i = 0; i < markers_on_map.length; i++) {
  		if (markers_on_map[i]) {
  			markers_on_map[i].setMap(null);
  			markers_on_map[i] = null;
  		}
  	}

  	if (geocoder) {
  		geocoder.geocode({'address': address}, function (results, status) {
  			if (status == google.maps.GeocoderStatus.OK) {
  				if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
  					var address_lat_lng = results[0].geometry.location;
  					radius_circle = new google.maps.Circle({
  						center: address_lat_lng,
  						radius: radius_km * 1000,
  						clickable: false,
						map: map
  					});
                    if (radius_circle) map.fitBounds(radius_circle.getBounds());
  					for (var j = 0; j < all_locations.length; j++) {
  						(function (location) {
  							var marker_lat_lng = new google.maps.LatLng(location.lat, location.lng);
  							var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(address_lat_lng, marker_lat_lng); //distance in meters between your location and the marker
  							if (location_type == location.type && distance_from_location <= radius_km * 1000) {
  								var new_marker = new google.maps.Marker({
  									position: marker_lat_lng,
  									map: map,
  									title: location.name
  								});      								google.maps.event.addListener(new_marker, 'click', function () {
                                    if(infowindow){
             infowindow.setMap(null);
             infowindow = null;
           }
  									infowindow = new google.maps.InfoWindow(
            { content: '<div style="color:red">'+location.name +'</div>' + " is " + distance_from_location + " meters from my location",
              size: new google.maps.Size(150,50),
              pixelOffset: new google.maps.Size(0, -30)
            , position: marker_lat_lng, map: map});
  								});
  								markers_on_map.push(new_marker);
  							}
  						})(all_locations[j]);
  					}
  				} else {
  					alert("No results found while geocoding!");
  				}
  			} else {
  				alert("Geocode was not successful: " + status);
  			}
  		});
  	}
  }
  
  function getMyAdress() {
  	if (navigator.geolocation) {
  		navigator.geolocation.getCurrentPosition(function (position) {
  			geocoder.geocode({latLng: new google.maps.LatLng(position.coords.latitude, position.coords.longitude)}, function (results, status) {
  				if (status == google.maps.GeocoderStatus.OK) {
  					if (results[0]) {
  						$('#address').val(results[0].formatted_address);
  					} else {
  						alert("No results found");
  					}
  				} else {
  					alert("Geocode was not successful for the following reason: " + status);
  				}
  			});
  		}, function () {
  			alert("Unable to find my location!");
  		});
  	}
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
        google.load("maps", "3",{other_params:"sensor=false&libraries=geometry"});
      </script>

<body style="margin:0px; padding:0px;" >
 <input id="address" value="Second Steet, New York" placeholder="Input Address"/>
 <select id="radius_km">
	 <option value=1>1km</option>
	 <option value=2>2km</option>
	 <option value=5>5km</option>
	 <option value=30>30km</option>
 </select>
 <select id="location_type">
	 <option value="restaurant">Restaurant</option>
	 <option value="school">School</option>
 </select>
 <button onClick="getMyAdress()">Get My Location</button>
 <button onClick="showCloseLocations()">Show Locations In Radius</button>
 <div id="map_canvas"  style="width:500px; height:300px;">
</body>
</html>

这篇关于如何将Google Map API用于Web?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆