javascript - 使用 php/Wordpress 中的 google place api 获取附近的位置

标签 javascript jquery wordpress google-maps

$(document).ready(function() {
  var image_src = "images/";
  var map;
  var infowindow;
  var bounds = new google.maps.LatLngBounds();

  var PlaceArray = ["restaurant", "cafe", "bar", "grocery_or_supermarket", "parks", "school", "shopping_mall", "movie_theater", "bank", "university"];
  var PlaceCounter = 0;

  function initialize() {
    "use strict";
    var pyrmont = new google.maps.LatLng(40.5456, -74.4608);

    map = new google.maps.Map(document.getElementById('googleMapNearestPlaces'), {
      center: pyrmont,
      zoom: 14,
      icon: 'images/map_marker.png',
      scrollwheel: false,
      rankby: 'distance',
      styles: [{
        "featureType": "all",
        "elementType": "geometry",
        "stylers": [{
          "color": "#00c775"
        }]
      }, {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": [{
          "gamma": 0.01
        }, {
          "lightness": 20
        }]
      }, {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": [{
          "saturation": -31
        }, {
          "lightness": -33
        }, {
          "weight": 2
        }, {
          "gamma": 0.8
        }]
      }, {
        "featureType": "all",
        "elementType": "labels.icon",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "all",
        "stylers": [{
          "visibility": "on"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "labels",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "landscape",
        "elementType": "all",
        "stylers": [{
          "visibility": "simplified"
        }, {
          "color": "#ffffff"
        }]
      }, {
        "featureType": "landscape",
        "elementType": "geometry",
        "stylers": [{
          "lightness": 30
        }, {
          "saturation": 30
        }]
      }, {
        "featureType": "poi",
        "elementType": "all",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "poi",
        "elementType": "geometry",
        "stylers": [{
          "saturation": 20
        }]
      }, {
        "featureType": "poi.park",
        "elementType": "geometry",
        "stylers": [{
          "lightness": 20
        }, {
          "saturation": -20
        }]
      }, {
        "featureType": "road",
        "elementType": "all",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": [{
          "lightness": 10
        }, {
          "saturation": -30
        }]
      }, {
        "featureType": "road",
        "elementType": "geometry.stroke",
        "stylers": [{
          "saturation": 25
        }, {
          "lightness": 25
        }]
      }, {
        "featureType": "transit",
        "elementType": "all",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "water",
        "elementType": "all",
        "stylers": [{
          "lightness": "0"
        }, {
          "visibility": "on"
        }, {
          "color": "#00c775"
        }, {
          "gamma": "1"
        }, {
          "weight": "1"
        }]
      }, {
        "featureType": "water",
        "elementType": "labels",
        "stylers": [{
          "visibility": "off"
        }]
      }]
    });

    var marker = new google.maps.Marker({
      position: pyrmont,
      icon: 'images/map_marker.png'
    });
    marker.setMap(map);
    var request = {
      location: pyrmont,
      radius: 5000,
      types: ["restaurant", "cafe", "bar", "grocery_or_supermarket", "parks", "school", "shopping_mall", "movie_theater", "bank", "university"],
    };

    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);
  }

  function callback(results, status) {
    "use strict";
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
  }

  function createMarker(place) {
    "use strict";
    var place_icon;
    place_icon = "images/map-icons/" + place.types['0'] + ".png";

    var PlaceType = place.types['0'];

    if (jQuery.inArray(PlaceType, PlaceArray) == -1) {
      return;
    }

    PlaceArray = jQuery.grep(PlaceArray, function(value) {
      return value != PlaceType;
    });

    var Distance = distance(place.geometry.location.lat(), place.geometry.location.lng());

    function distance(latitude2, longitude2) {
      var lat1 = "40.5456";
      var lon1 = "-74.4608";
      var lat2 = latitude2;
      var lon2 = longitude2;

      var radlat1 = Math.PI * lat1 / 180;
      var radlat2 = Math.PI * lat2 / 180;
      var radlon1 = Math.PI * lon1 / 180;
      var radlon2 = Math.PI * lon2 / 180;
      var theta = lon1 - lon2;
      var radtheta = Math.PI * theta / 180;
      var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
      dist = Math.acos(dist);
      dist = dist * 180 / Math.PI;
      dist = dist * 60 * 1.1515;

      dist = dist * 1.609344;

      return Math.round(dist * 100) / 100;
    }

    if (PlaceType == "cafe") {
      PlaceType = "Cofee";
    }
    if (PlaceType == "grocery_or_supermarket") {
      PlaceType = "Groceries";
    }
    if (PlaceType == "shopping_mall") {
      PlaceType = "Shopping";
    }
    if (PlaceType == "movie_theater") {
      PlaceType = "Entertainment";
    }
    if (PlaceType == "bank") {
      PlaceType = "Errands";
    }

    jQuery("#near-by-place-detail").append("<ul><li class='left'><p><b>" + PlaceType.charAt(0).toUpperCase() + PlaceType.substr(1) + "</b></p><span>" + place.name + "</span></li><li class='right'><label>" + Distance + " Km</label></li></ul>");

    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
      map: map,
      position: place.geometry.location,
      icon: place_icon,
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent(place.name);
      infowindow.open(map, this);
    });

    bounds.extend(marker.position);

    //now fit the map to the newly inclusive bounds
    map.fitBounds(bounds);

    //(optional) restore the zoom level after the map is done scaling
    var listener = google.maps.event.addListener(map, "idle", function() {
      map.setZoom(12);
      google.maps.event.removeListener(listener);
    });

  }
  google.maps.event.addDomListener(window, 'load', initialize);
});
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<section class="near_by_places">
  <div class="container">
    <h2>Near By Places</h2>
    <div class="row">
      <div id="near-by-place-detail" class="col-xs-12 col-sm-4 col-md-4"></div>
      <div class="near-by-place-map col-xs-12 col-sm-8 col-md-8">
        <div id="googleMapNearestPlaces" style="width:100%;height:100%;"></div>
      </div>
    </div>
  </div>
</section>

此代码不起作用,并且位置附近未加载 map 。我已经尝试过上面的代码,但它没有在附近的地方加载。任何人都知道如何加载 WordPress 中附近的位置。我还使用过 Google Api 库。

最佳答案

$(document).ready(function(){
	var image_src = "images/";
	var map;
	var infowindow;
	var bounds = new google.maps.LatLngBounds();

	var PlaceArray = [ "restaurant", "cafe", "bar", "grocery_or_supermarket", "parks", "school", "shopping_mall", "movie_theater", "bank", "university"];
	var PlaceCounter = 0;

	function initialize() {
		"use strict";
		var pyrmont = new google.maps.LatLng(40.5456, -74.4608);

		map = new google.maps.Map(document.getElementById('googleMapNearestPlaces'), {
			center: pyrmont,
			zoom: 14,
			icon:'images/map_marker.png',
			scrollwheel: false,
			rankby: 'distance',
			styles: [{"featureType":"all","elementType":"geometry","stylers":[{"color":"#00c775"}]},{"featureType":"all","elementType":"labels.text.fill","stylers":[{"gamma":0.01},{"lightness":20}]},{"featureType":"all","elementType":"labels.text.stroke","stylers":[{"saturation":-31},{"lightness":-33},{"weight":2},{"gamma":0.8}]},{"featureType":"all","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"administrative","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape","elementType":"all","stylers":[{"visibility":"simplified"},{"color":"#ffffff"}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"lightness":30},{"saturation":30}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"saturation":20}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"lightness":20},{"saturation":-20}]},{"featureType":"road","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":10},{"saturation":-30}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"saturation":25},{"lightness":25}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"lightness":"0"},{"visibility":"on"},{"color":"#00c775"},{"gamma":"1"},{"weight":"1"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"off"}]}]		
		});

		var marker=new google.maps.Marker({position:pyrmont,icon:'images/map_marker.png'});
		marker.setMap(map);
		var request = {
			location: pyrmont,
			radius: 5000,
			types: [ "restaurant", "cafe", "bar", "grocery_or_supermarket", "parks", "school", "shopping_mall", "movie_theater", "bank", "university"],
		};

		infowindow = new google.maps.InfoWindow();
		var service = new google.maps.places.PlacesService(map);
		service.nearbySearch(request, callback);
	}

	function callback(results, status) {
		"use strict";
		if (status == google.maps.places.PlacesServiceStatus.OK) {
			for (var i = 0; i < results.length; i++) {
				createMarker(results[i]);
			}
		}
	}

	function createMarker(place) {
		"use strict";
		var place_icon;
		place_icon =  "images/map-icons/" + place.types['0'] + ".png";
		
		var PlaceType = place.types['0'];

		if( jQuery.inArray( PlaceType, PlaceArray ) == -1 ){
			return;
		}
		
		PlaceArray = jQuery.grep(PlaceArray, function(value) {
		  return value != PlaceType;
		});

		var Distance = distance(place.geometry.location.lat(),place.geometry.location.lng());

		function distance(latitude2, longitude2) {
			var lat1 = "40.5456";
			var lon1 = "-74.4608";
			var lat2 = latitude2;
			var lon2 = longitude2;
			
			var radlat1 = Math.PI * lat1/180;
			var radlat2 = Math.PI * lat2/180;
			var radlon1 = Math.PI * lon1/180;
			var radlon2 = Math.PI * lon2/180;
			var theta = lon1-lon2;
			var radtheta = Math.PI * theta/180;
			var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
			dist = Math.acos(dist);
			dist = dist * 180/Math.PI;
			dist = dist * 60 * 1.1515;

			dist = dist * 1.609344;
			
			return Math.round( dist * 100 )/100;
		}
			
		if( PlaceType == "cafe"){
			PlaceType = "Cofee";
		}
		if( PlaceType == "grocery_or_supermarket"){
			PlaceType = "Groceries";
		}
		if( PlaceType == "shopping_mall"){
			PlaceType = "Shopping";
		}
		if( PlaceType == "movie_theater"){
			PlaceType = "Entertainment";
		}
		if( PlaceType == "bank"){
			PlaceType = "Errands";
		}

		jQuery("#near-by-place-detail").append("<ul><li class='left'><p><b>"+PlaceType.charAt(0).toUpperCase() + PlaceType.substr(1)+"</b></p><span>"+place.name+"</span></li><li class='right'><label>"+Distance+" Km</label></li></ul>");

		var placeLoc = place.geometry.location;
		var marker = new google.maps.Marker({
			map: map,
			position: place.geometry.location,
			icon:place_icon,
		});

		google.maps.event.addListener(marker, 'click', function() {
			infowindow.setContent(place.name);
			infowindow.open(map, this);
		});

		bounds.extend(marker.position);

		//now fit the map to the newly inclusive bounds
		map.fitBounds(bounds);

		//(optional) restore the zoom level after the map is done scaling
		var listener = google.maps.event.addListener(map, "idle", function () {
		    map.setZoom(12);
		    google.maps.event.removeListener(listener);
		});

	}
	google.maps.event.addDomListener(window, 'load', initialize);
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<section class="near_by_places">
			<div class="container">
				<h2>Near By Places</h2>
				<div class="row">
					<div id="near-by-place-detail" class="col-xs-12 col-sm-4 col-md-4"></div>
					<div class="near-by-place-map col-xs-12 col-sm-8 col-md-8">
						<div id="googleMapNearestPlaces" style="width:100%;height:100%;"></div>
					</div>
				</div>
			</div>
</section>

关于javascript - 使用 php/Wordpress 中的 google place api 获取附近的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37404780/

相关文章:

wordpress - 如何去除联系表 7 中的跨度 wrapper ?

wordpress - 将每 2 个 WordPress 帖子包含在 Bootstrap Row 类中

javascript - 为什么modal弹出按空格键会按?我该如何预防?

javascript - if语句在javascript中查找类

jquery - 在 jquery ui 中放置后单击对象

javascript - 将 JavaScript 传递给局部 View

javascript - 从 EmberJs 组件进行 ajax 调用的正确方法?

javascript - Woocommerce,将产品添加到购物车,请求失败

javascript - 使用jQuery测试数组中是否存在具有属性的对象

javascript - Moment JS:如何将 MM/DD/YYYY 中的日期解析为 DD/MM/YYYY