Попытка отобразить несколько карт Google на одной странице с помощью jquery - PullRequest
0 голосов
/ 27 сентября 2019

В настоящее время я делаю поиск ресторана с помощью API Zomato и пытаюсь отобразить местоположение каждого ресторана с помощью API карт Google.Но по какой-то причине API отображается только на 1-м результате, но не на других.

Для API карт Google в настоящее время я использую плагин, который я получил отсюда: https://tilotiti.github.io/jQuery-Google-Map/

Код ниже является лишь частью этого.Ссылка на полную рабочую демонстрацию приведена ниже.

JQuery

$(document).ready(function() {

 $("#getMessage").on("click", function() {
  var valueSearchBox = $('#getText').val()
  if (valueSearchBox === "") {
   return;
  }
  select();
 });


 function select() {
  var valueDropdown = "Melbourne"
  var valueSearchBox = $('#getText').val()
  var searchCity = "&q=" + valueSearchBox;
  var settings = {
   "async": true,
   "crossDomain": true,
   "url": "https://developers.zomato.com/api/v2.1/search?entity_id=" + valueDropdown + "&entity_type=city" + searchCity + "&count=100",
   "method": "GET",
   "headers": {
    "user-key": "KEY",
    'Content-Type': 'application/x-www-form-urlencoded'
   }
  }

  $.getJSON(settings, function(data) {

   data = data.restaurants;
   var html = "";

   $.each(data, function(index, value) {

    var x = data[index];
    $.each(x, function(index, value) {
     var location = x.restaurant.location;
     var userRating = x.restaurant.user_rating;
     html += "<div class='data img-rounded'>";
     html += "<div class='rating'>";

     html += "<span title='" + userRating.rating_text + "'><p style='color:white;background-color:#" + userRating.rating_color + ";border-radius:4px;border:none;padding:2px 10px 2px 10px;text-align: center;text-decoration:none;display:inline-block;font-size:16px;float:right;'><strong>" + userRating.aggregate_rating + "</strong></p></span><br>";
     html += "  <strong class='text-info'>" + userRating.votes + " votes</strong>";
     html += "</div>";
     html += "<img class='resimg img-rounded' src=" + value.thumb + " alt='Restaurant Image' height='185' width='185'>";
     html += "<a href=" + value.url + " target='_blank' class='action_link'><h2 style='color:red;'><strong>" + value.name + "</strong></h2></a>";
     html += "  <strong class='text-primary'>" + location.locality + "</strong><br>";
     html += "  <h6 style='color:grey;'><strong>" + location.address + "</strong></h6><hr>";
     html += "  <strong>CUISINES</strong>: " + value.cuisines + "<br>";
     html += "  <strong>COST FOR TWO</strong>: " + value.currency + value.average_cost_for_two + "<br>";
     html += "<div id='map' style='width: 300px; height: 300px;'></div>";
     html += "</div><br>";

     //function calling the google maps JS plugin
     $(function() {
            $("#map").googleMap();
            $("#map").addMarker({
                coords: [48.895651, 2.290569],
                id: 'marker1' // Unique ID for your marker
            });
        });
    });
   });
   $(".message").html(html);
  });

 }
 //--------------------------------------------------------------------------------------------------------
 $("#select_id").change(function() {
  select();
 });
});

Ссылка на демонстрационный код моего кода: https://jsfiddle.net/CY1223/qzdrsykw/1/

Просто введите любое связанное с едой слово, например:"Пицца" и нажмите кнопку поиска.

1 Ответ

0 голосов
/ 27 сентября 2019

На HTML-странице может быть только один <div> с id = "map" ($("#map").googleMap();).Если вам нужны мультипликаторы, добавьте уникальность (#map1) или используйте что-то, что не обязательно должно быть уникальным (class=map).

html += "<div class='map' style='width: 300px; height: 300px;'></div>";
 //function calling the google maps JS plugin
 $(function() {
        $(".map").googleMap();
        $(".map").addMarker({
            coords: [48.895651, 2.290569],
            id: 'marker1' // Unique ID for your marker
        });
    })

подтверждение концепции скрипта

фрагмент кода:

$(function() {

	$.fn.googleMap = function(params) {
		params = $.extend( {
			zoom : 10,
			coords : [48.895651, 2.290569],
			type : "ROADMAP",
			debug : false,
			langage : "english",
			overviewMapControl: false,
			streetViewControl: false,
			scrollwheel: false,
			mapTypeControl: false
		}, params);

		switch(params.type) {
			case 'ROADMAP':
			case 'SATELLITE':
			case 'HYBRID':
			case 'TERRAIN':
				params.type = google.maps.MapTypeId[params.type];
				break;
			default:
				params.type = google.maps.MapTypeId.ROADMAP;
				break;
		}

		this.each(function() {

			var map = new google.maps.Map(this, {
				zoom: params.zoom,
				center: new google.maps.LatLng(params.coords[0], params.coords[1]),
				mapTypeId: params.type,
				scrollwheel: params.scrollwheel,
				streetViewControl: params.streetViewControl,
				overviewMapControl: params.overviewMapControl,
				mapTypeControl: params.mapTypeControl

			});

			$(this).data('googleMap', map);
			$(this).data('googleLang', params.langage);
			$(this).data('googleDebug', params.debug);
			$(this).data('googleMarker', new Array());
			$(this).data('googleBound', new google.maps.LatLngBounds());
		});

		return this;
	}

	$.fn.addMarker = function(params) {
		params = $.extend( {
			coords : false,
			address : false,
			url : false,
			id : false,
			icon : false,
			draggable : false,
			title : "",
			text : "",
			success : function() {}
		}, params);

		this.each(function() {
			$this = $(this);

			if(!$this.data('googleMap')) {
				if($this.data('googleDebug'))
					console.error("jQuery googleMap : Unable to add a marker where there is no map !");
					
				return false;
			}

			if(!params.coords && !params.address) {
				if($this.data('googleDebug'))
					console.error("jQuery googleMap : Unable to add a marker if you don't tell us where !");
					
				return false;
			}

			if(params.address && typeof params.address == "string") {

				var geocodeAsync = function($that) {

					var geocoder = new google.maps.Geocoder();

					geocoder.geocode({
						address : params.address,
						bounds : $that.data('googleBound'),
						language : $that.data('googleLang')
					}, function(results, status) {

						if (status == google.maps.GeocoderStatus.OK) {
							$that.data('googleBound').extend(results[0].geometry.location);

							if(params.icon) {
								var marker = new google.maps.Marker({
									map: $this.data('googleMap'),
									position: results[0].geometry.location,
									title: params.title,
									icon: params.icon,
									draggable: params.draggable
								});
							} else {
								var marker = new google.maps.Marker({
									map: $that.data('googleMap'),
									position: results[0].geometry.location,
									title: params.title,
									draggable: params.draggable
								});
							}

							if(params.draggable) {
								google.maps.event.addListener(marker, 'dragend', function() {
									var location = marker.getPosition();

									var coords = {};

									coords.lat = location.lat();
									coords.lon = location.lng();

									params.success(coords, $this);
								});
							}

							if(params.title != "" && params.text != "" && !params.url) {
								var infowindow = new google.maps.InfoWindow({
									content: "<h1>"+params.title+"</h1>"+params.text
								});

								var map = $that.data('googleMap');
                                previous_infowindow = null;
								google.maps.event.addListener(marker, 'click', function() {
                                    if(previous_infowindow!==null)
                                        previous_infowindow.close(map, marker);
									infowindow.open(map, marker);
                                    previous_infowindow=infowindow;
								});
							} else if(params.url) {
								google.maps.event.addListener(marker, 'click', function() {
									document.location = params.url;
								});
							}

							if(!params.id) {
								$that.data('googleMarker').push(marker);
							} else {
								$that.data('googleMarker')[params.id] = marker;
							}

							if($that.data('googleMarker').length == 1) {
								$that.data('googleMap').setCenter(results[0].geometry.location);
								$that.data('googleMap').setZoom($that.data('googleMap').getZoom());
							} else {
								$that.data('googleMap').fitBounds($that.data('googleBound'));
							}

							var coords = {};
							coords.lat = results[0].geometry.location.lat();
							coords.lon = results[0].geometry.location.lng();
																					
							for(var i in results[0].address_components) {
								if(results[0].address_components[i].types.indexOf("postal_code") > -1) {
									coords.zipcode = results[0].address_components[i].long_name;
								}
							}

							params.success(coords, $this);

						} else {
							if($this.data('googleDebug'))
								console.error("jQuery googleMap : Unable to find the place asked for the marker ("+status+")");
						}
					});
				}($this);
			} else {
				$this.data('googleBound').extend(new google.maps.LatLng(params.coords[0], params.coords[1]));

        			if(params.icon) {
					var marker = new google.maps.Marker({
						map: $this.data('googleMap'),
						position: new google.maps.LatLng(params.coords[0], params.coords[1]),
						title: params.title,
						icon: params.icon,
						draggable: params.draggable
					});
				} else {
					var marker = new google.maps.Marker({
						map: $this.data('googleMap'),
						position: new google.maps.LatLng(params.coords[0], params.coords[1]),
						title: params.title,
						draggable: params.draggable
					});
				}

        			if(params.title != "" && params.text != "" && !params.url) {
          				var infowindow = new google.maps.InfoWindow({
						content: "<h1>"+params.title+"</h1>"+params.text
					});

					var map = $this.data('googleMap');
                    previous_infowindow = null;
	        			google.maps.event.addListener(marker, 'click', function() {
                            if(previous_infowindow!==null)
                                previous_infowindow.close(map, marker);
		        			infowindow.open(map, marker);
                            previous_infowindow=infowindow;
	        			});
				} else if(params.url) {
          				google.maps.event.addListener(marker, 'click', function() {
              					document.location = params.url;
        				});
				}

				if(params.draggable) {
					google.maps.event.addListener(marker, 'dragend', function() {
						var location = marker.getPosition();

						var coords = {};

						coords.lat = location.lat();
						coords.lon = location.lng();

						params.success(coords, $this);
					});
				}

				if(!params.id) {
       					$this.data('googleMarker').push(marker);
        			} else {
        				$this.data('googleMarker')[params.id] = marker;
        			}

				if($this.data('googleMarker').length == 1) {
					$this.data('googleMap').setCenter(new google.maps.LatLng(params.coords[0], params.coords[1]));
					$this.data('googleMap').setZoom($this.data('googleMap').getZoom());
				} else {
					$this.data('googleMap').fitBounds($this.data('googleBound'));
				}

				params.success({
					lat: params.coords[0],
					lon: params.coords[1]
				}, $this);
			}
		});

		return this;
	}

	$.fn.removeMarker = function(id) {
		this.each(function() {
			var $this = $(this);

    			if(!$this.data('googleMap')) {
    				if($this.data('googleDebug'))
      					console.log("jQuery googleMap : Unable to delete a marker where there is no map !");
      					
      				return false;
    			}

    			var $markers = $this.data('googleMarker');

    			if(typeof $markers[id] != 'undefined') {
    				$markers[id].setMap(null);
    				
      				if($this.data('googleDebug'))
      					console.log('jQuery googleMap : marker deleted');
      					
      				return true;
    			} else {
      				if($this.data('googleDebug'))
      					console.error("jQuery googleMap : Unable to delete a marker if it not exists !");
      		
      				return false;
    			}
		});
	}

	$.fn.addWay = function(params) {
		params = $.extend( {
			start : false,
			end : false,
			step : [],
			route : false,
			langage : 'english'
		}, params);

		var direction = new google.maps.DirectionsService({
			region: "fr"
		});

		var way = new google.maps.DirectionsRenderer({
			draggable: true,
			map: $(this).data('googleMap'),
			panel: document.getElementById(params.route),
			provideTripAlternatives: true
		});
		
		document.getElementById.innerHTML = "";

		var waypoints = [];

    		for(var i in params.step) {
    			var step;
      			if(typeof params.step[i] == "object") {
        			step = new google.maps.LatLng(params.step[i][0], params.step[i][1]);
      			} else {
        			step = params.step[i];
      			}

      			waypoints.push({
      				location: step,
      				stopover: true
      			});
		}

		if(typeof params.end != "object") {
			var geocodeAsync = function($that) {
				var geocoder = new google.maps.Geocoder();

		    		geocoder.geocode({
		    			address  : params.end,
		    			bounds   : $that.data('googleBound'),
		    			language : params.langage
		    		}, function(results, status) {
	        			if (status == google.maps.GeocoderStatus.OK) {
	        				var request = {
	            					origin: params.start,
	            					destination: results[0].geometry.location,
	            					travelMode: google.maps.DirectionsTravelMode.DRIVING,
	            					region: "fr",
	            					waypoints: waypoints
		        			};

		        			direction.route(request, function(response, status) {
	            					if (status == google.maps.DirectionsStatus.OK) {
	              						way.setDirections(response);
	            					} else {
	              						if($that.data('googleDebug'))
	            							console.error("jQuery googleMap : Unable to find the place asked for the route ("+response+")");
	            					}
		        			});

	        			} else {
	          				if($that.data('googleDebug'))
	          					console.error("jQuery googleMap : Address not found");
	        			}
		    		});
	    		}($(this));
		} else {
			var request = {
				origin: params.start,
				destination: new google.maps.LatLng(params.end[0], params.end[1]),
				travelMode: google.maps.DirectionsTravelMode.DRIVING,
				region: "fr",
				waypoints: waypoints
			};

			direction.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					way.setDirections(response);
				} else {
					if($(this).data('googleDebug'))
          					console.error("jQuery googleMap : Address not found");
				}
			});
		}

		return this;
	}
});
.jumbotron-billboard .img {
  margin-bottom: 0px;
  opacity: 0.7;
  color: #fff;
  background: #000 url("https://cdn.fstoppers.com/styles/full/s3/media/2017/09/11/autumn_food_photography_0.jpg") top center no-repeat;
  width: 100%;
  height: 100%;
  background-size: cover;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.jumbotron h2 {
  margin-top: 0;
}

.jumbotron {
  position: relative;
  padding-top: 50px;
  padding-bottom: 50px;
}

.jumbotron .container {
  position: relative;
  z-index: 2;
}

@media screen and (max-width: 768px) {
  .jumbotron {
    padding-top: 20px;
    padding-bottom: 20px;
  }
}

.text-color {
  color: white;
}

.pt {
  padding-top: 75px;
}

.logo {
  width: 150px;
  height: 150px;
}

.data {
  padding-left: 50px;
  padding-right: 50px;
  padding-top: 10px;
  padding-bottom: 10px;
  background-color: #F5F5F5;
}

a.action_link {
  text-decoration: none;
}

.resimg {
  float: left;
  margin-right: 15px;
}

body {
  background-image: url("https://image.ibb.co/fqkgMw/dust_scratches.png");
}

.horizontal-center-row {
  display: flex;
  justify-content: center;
}

.rating {
  float: right;
  margin-right: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAkFB8OXnhc_C7U5tLheMpKCVtf3ROvzKM&callback"></script>
<script>

$(document).ready(function() {

 $("#getMessage").on("click", function() {
  var valueSearchBox = $('#getText').val()
  if (valueSearchBox === "") {
   return;
  }
  select();
 });
 //--------------------------------------------------SEARCH BY CITY-----------------------------------------

 function select() {
  var valueDropdown = "Melbourne"
  var valueSearchBox = $('#getText').val()
  var searchCity = "&q=" + valueSearchBox;
  var settings = {
   "async": true,
   "crossDomain": true,
   "url": "https://developers.zomato.com/api/v2.1/search?entity_id=" + valueDropdown + "&entity_type=city" + searchCity + "&count=100",
   "method": "GET",
   "headers": {
    "user-key": "39dc8aec87ae1aa4d4f9cfdcbea85961",
    'Content-Type': 'application/x-www-form-urlencoded'
   }
  }

  $.getJSON(settings, function(data) {

   data = data.restaurants;
   var html = "";

   $.each(data, function(index, value) {

    var x = data[index];
    $.each(x, function(index, value) {
     var location = x.restaurant.location;
     var userRating = x.restaurant.user_rating;
	 html += "<div class='data img-rounded'>";
     html += "<div class='rating'>";

     html += "<span title='" + userRating.rating_text + "'><p style='color:white;background-color:#" + userRating.rating_color + ";border-radius:4px;border:none;padding:2px 10px 2px 10px;text-align: center;text-decoration:none;display:inline-block;font-size:16px;float:right;'><strong>" + userRating.aggregate_rating + "</strong></p></span><br>";
     html += "  <strong class='text-info'>" + userRating.votes + " votes</strong>";
     html += "</div>";
     html += "<img class='resimg img-rounded' src=" + value.thumb + " alt='Restaurant Image' height='185' width='185'>";
     html += "<a href=" + value.url + " target='_blank' class='action_link'><h2 style='color:red;'><strong>" + value.name + "</strong></h2></a>";
     html += "  <strong class='text-primary'>" + location.locality + "</strong><br>";
     html += "  <h6 style='color:grey;'><strong>" + location.address + "</strong></h6><hr>";
     html += "  <strong>CUISINES</strong>: " + value.cuisines + "<br>";
     html += "  <strong>COST FOR TWO</strong>: " + value.currency + value.average_cost_for_two + "<br>";
	 html += "<div class='map' style='width: 300px; height: 300px;'></div>";
     html += "</div><br>";
	 
	 $(function() {
			$(".map").googleMap();
			$(".map").addMarker({
				coords: [48.895651, 2.290569],
				id: 'marker1' // Unique ID for your marker
			});
		});
    });
   });
   $(".message").html(html);
  });

 }
 //--------------------------------------------------------------------------------------------------------
 $("#select_id").change(function() {
  select();
 });
});
</script>
<link rel="stylesheet" type="text/css" href="css/CSS.css">
<div class="jumbotron jumbotron-billboard text-center">
	<div class="img"></div>
	<div class="container pt">
		<div class="text-center">
			<img class="logo" src='http://image.ibb.co/g52Ayb/Go_Food_2.png' />
		</div>
		<div class="mt-5 text-color">
			<h1>Find the best Restaurants</h1>
		</div>
		<div class="row mx-auto well col-lg-12 mt-5">
			<div class="col-xs-6 pl-0 pr-0">
				<input id="getText" type="text" class="form-control" placeholder="Search for Restaurant">
				</div>
				<button id = "getMessage" class = "btn btn-success col-xs-2">Search</button>
			</div>
		</div>
	</div>
	<div class="container">
		<div>
			<div class = "message col-md-12"></div>
		</div>
	</div>
	<hr>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...