Google Maps API with multiple markers / modals - javascript

I am using the Google Maps API JS v.3 that has several hundred markers. I want to open a modal with info specific to the marker they clicked on. I'm plan on using PHP and AJAX to get the modal data from the MySQL Database, but I'm not sure how to determine which marker the user clicked...
Any help is greatly appreciated
`
var map;
//icon variables
/*
var dem = 'path/to/blue/icon.png';
var rep = 'path/to/red/icon.png';
var oth = 'path/to/grey/icon.png';
*/
var locations = [
<?php
$c = 0;
$nr = mysqli_num_rows($gethouses);
while($z = mysqli_fetch_array($gethouses)):
?>
['<?php echo $z['name_first'].' '.$z['name_last']; ?>', <?php echo $z['lat']; ?>, <?php echo $z['lng']; ?>, 4],
<?php
$c++;
endwhile;
?>
];
var map = new google.maps.Map(document.getElementById('google_world_map'), {
zoom: 10,
center: new google.maps.LatLng(39.675, -119.98),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
function AutoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
// Fit these bounds to the map
map.fitBounds(bounds);
}
AutoCenter();
</script>`

You can add a custom parameter in your marker object (which value ideally should be unique).
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
custom_param: some_unique_value
});
....
}
Then on your marker click event you can identify which marker is clicked by getting the value in this case marker.custom_param.
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
// make use of `marker.custom_param`
var myCustomParam = marker.custom_param;
}
})(marker, i));
}

Related

Multiple markers are not properly showing in google map php

In my laravel project am trying to show locations of my clinics in google maps (Taking lattitude and longitude values from php database). Follwoing is my code in controller.
public function showClinicLocations($id)
{
$clinic = Clinic::find($id);
$locations = Location::where('clinicID', $id)->get();
return view('clinic.locations')->with(['locations' => $locations ,'clinic'=>$clinic]);
}
In view page am properly getting locations .When i consoled the locations.length am getting the result as 12 , its correct and also am getting complete locations name.
But when i tried to show it in marker only 11 locations are showing in google map marker. Following is the code in google map marker.
<script>
// var services =<?php echo json_encode($services);?>;
// console.log(services);
function initMap() {
var locations = <?php echo $locations ?>;
console.log(locations.length);
var j;
for (j = 0; j < locations.length; j++) {
var map = new google.maps.Map(document.getElementById('map'),
{zoom: 8,
center: {
lat: parseFloat(locations[j]['locationLat']),
lng:parseFloat(locations[j]['locationLong'])
}
}
);
setMarkers(map);
}
}
function setMarkers(map) {
var locations = <?php echo $locations ?>;
//var services = <?php echo $services ?>;
//console.log(services);
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
map: map,
position: {lat: parseFloat(locations[i]['locationLat']), lng:parseFloat(locations[i]['locationLong'])},
map: map,
title: locations[i]['locationName']
});
var infowindow = new google.maps.InfoWindow()
var content = locations[i]['locationName'];
google.maps.event.addListener(marker,'click',
(function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker, content,infowindow));
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>
What is the problem with the code of google maps to show markers
You wanna generate the map only once and maybe also fit the map to the bounds of all displayed markers:
var locations = JSON.parse("<?php echo $locations ?>");
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: {
lat: parseFloat(locations[0]["locationLat"]),
lng: parseFloat(locations[0]["locationLong"])
}
});
setMarkers(map);
}
function setMarkers(_map) {
var boundsToFit = new google.maps.LatLngBounds();
for (var i = 0; i <= locations.length; i++) {
var marker = new google.maps.Marker({
map: _map,
position: {
lat: parseFloat(locations[i]["locationLat"]),
lng: parseFloat(locations[i]["locationLong"])
},
map: _map,
title: locations[i]["locationName"]
});
var infowindow = new google.maps.InfoWindow();
var content = locations[i]["locationName"];
google.maps.event.addListener(
marker,
"click",
(function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(_map, marker);
};
})(marker, content, infowindow)
);
boundsToFit.extend(marker.getPosition());
}
_map.fitBounds(boundsToFit);
}

Pass PHP Array to Google Maps Markers (Javascript)

I'm storing my data to a php array and trying to pass it to javascript to get google maps display all the points in the php array. bellow is the php code (simplified and the javascript code for google maps.
-----PHP CODE--------
foreach(json_decode($response)->data as $item){
$name= $item->user->name;
$latitude = $item->latitude;
$longitude = $item->longitude;
$Array[$count] = array('name'=>$name,'lat'=>$latitude, 'long'=>$longitude, 'rgb'=>$count);
$js_array = json_encode($Array);
$count++;}
-----javascript
<script type="text/javascript">
var locations = <?php echo $js_array;?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
UPDATED JAVASCRIPT
var locations = <?php echo json_encode($js_array);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(<?php echo $latitude;?>, <?php echo $longitude;?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i].lat);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].long),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].name);
infowindow.open(map, marker);
}
})(marker, i));
}
In your updated javascript, you need to remove json_encode (already present in PHP). You were doing it twice.

Place multiple php vars as lat/long in Google Maps

This is what I have... PHP pulls down 10 pairs of lat/long from an API url which I have managed to get working okay but I cannot seem to plot them on a map with multiple markers labelled 1-10.
My php code:
<?php
// Loading Domus API
$url_search = 'http://url/site/go/api/search';
$xml_search = #simplexml_load_file($url_search) or die ("no file loaded") ;
//Displaying latitude and longutude
$house = json_encode($house);
}; ?>
JavaScript bit:
var locations = "<?php foreach($xml_search->property as $house) { echo $lat = $house->address->latitude , $long = $house->address->longitude;}; ?>";
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(37.0625,-95.677068),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
Which is then needs to be displayed in here
<div id="map" style="width: 500px; height: 400px"></div>
But I just get a blank page, of course.
Okay, I've managed to figure it out.
Here is my php code in the head part
<?php
// Loading Domus API
$url_search = 'http://url/site/go/api/search';
$xml_search = #simplexml_load_file($url_search) or die ("no file loaded") ;?>
Then I have my javascript
// Load property ID followed by Lat and Long for each house (total of 10)
var locations = [<?php foreach($xml_search->property as $house) {
echo '['.$house->id. ',' .$house->address->latitude. ',' .$house->address->longitude.'],';
} ?>];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
function AutoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
$.each(markers, function (index, marker) {
bounds.extend(marker.position);
});
// Fit these bounds to the map
map.fitBounds(bounds);
}
AutoCenter();
Works beautifully, now just need to set up labelled markers and I am good to go.

Display a map (google) within a marker infowindow

I try to display a small map within a google map infowindow. The purpose is once the user click on the marker, an infowindow opens with a small map in it displaying the satellite view. The main code below is working quite well. The only thing is that I have an empty 'map_loc' because I don't know where to put the 'var map_loc'.
I'm using a query in a while loop from a mysql database to get the informations required.
Basically my question is, where do I have to put that portion of code in the main code below to display the small map named 'map_loc' which the div is in the marker 'locations':
var map_loc = new google.maps.Map(document.getElementById('map_loc'), {
zoom: 17,
center: new google.maps.LatLng(<?php echo $latlng_loc?>),
mapTypeId: google.maps.MapTypeId.SATELLITE
});
-
<div id="map" style="width:600px; height:600px;"></div>
<script type="text/javascript">
var locations = [
<?php
while ($x = $req->fetch())
{
// variables obtained :
$name = $d['name'];
$latlng_loc = $d['latlng']; // I need it to display the marker at the good location but also now to display the map within the infowindow
?>
['<h3><?php echo $name;?></h3><div id="loc_map" style="width:250px; height:150px;"></div>', <?php echo $latlng_loc?>],<?php
}
?>
];
// here is the main map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(<?php echo $latlng?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
Thanks for any help.
infowindow of google map, It can be use HTML intent .. try this:
example to 1 marker:
var content1 = '<div id="smallmap1"></div>';
var map_loc;
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(content1);
infowindow.open(map, marker);
set_small_map(i);
}
})(marker, i));
//"smallmap"+i == smallmap1, if i == 1;
function set_small_map(i){
map_loc = new google.maps.Map(document.getElementById("smallmap"+i), {
zoom: 17,
center: new google.maps.LatLng(<?php echo $latlng_loc?>),
mapTypeId: google.maps.MapTypeId.SATELLITE
});
};

How to change the image for a set of map markers

I am creating a map with 5 groups of markers. I have all the coordinates in place and the markers appear on the map, but I am not sure how to change the image for each group. I have looked at other examples, but they have not worked for me. If there is a way to change the image for either the group of coordinates or each individual coordinate, I would appreciate the help.
Here is what I have so far:
<script type="text/javascript"> function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(31.5603, -91.4031),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var cottages = [
['Savannah Cottage<br />412 S.Pearl Street', 31.55600224874313, -91.4073497056961] ];
var restaurants = [
['Cotton Alley Cafe<br />208 Main Street<br />(601)442-7452<br />Website', 31.561075,-91.40503100000001]
];
var bars = [
['Under-the-Hill Saloon', 31.559589, -91.41074700000001]
];
var tours = [
['Auburn Antebullum Home<br />400 Duncan Avenue<br />(601)442-5981', 31.5457833, -91.39274319999998]
];
var spas = [
['Anruss & Co Salon and Spa<br />212 North Commerce Street<br />(601) 445-2007<br />Website', 31.561061,-91.40116799999998]
];
//declare marker call it 'i'
var marker, i;
//declare infowindow
var infowindow = new google.maps.InfoWindow();
//add marker for COTTAGES
for (i = 0; i < cottages.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cottages[i][1], cottages[i][2]),
map: map,
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cottages[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
//add markers for RESTAURANTS
for (i = 0; i < restaurants.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(restaurants[i][1], restaurants[i][2]),
map: map,
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(restaurants[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
//add markers for BARS
for (i = 0; i < bars.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(bars[i][1], bars[i][2]),
map: map,
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(bars[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
//add markers for TOURS
for (i = 0; i < tours.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(tours[i][1], tours[i][2]),
map: map,
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(tours[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
//add markers for SPAS
for (i = 0; i < spas.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(spas[i][1], spas[i][2]),
map: map,
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(spas[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm not sure exactly what you have in mind but here's some code that may help :
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(31.5603, -91.4031),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//create infowindow
var infowindow = new google.maps.InfoWindow();
//add locations (as in the question)
var cottages = [...];
var restaurants = [...];
var bars = [...];
var tours = [...];
var spas = [...];
//Make an array that lists all the locations arrays.
var allLocations = [cottages, restaurants, bars, tours, spas];
//Define a generalized click handler for all markers.
//ie. one handler, not one per marker.
function clickMarker() {
var data = this.data;
infowindow.setContent(data.category[data.index][0]);
infowindow.open(map, this);
//HERE, you can loop through `data.category.markers` and
//do whatever is necessary to each marker in the category
//eg change their icons.
for(var i=0; i<data.category.markers.length; i++) {
var url = ...;//expression that determines which marker icon to use
data.category.markers[i].setIcon(url);
}
}
//Now loop through all the markers arrays and add markers to the map
for (var i=0; i<allLocations.length; i++) {
var arr = allLocations[i];
//Create an associated array in which to store references to category's markers
arr.markers = [];
for (var marker, j=0; j<arr.length; j++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(arr[j][1], arr[j][2]),
map: map
});
arr.markers[j] = marker;
//This allows the click hander to be generalized,
//and for each marker to have a reference back
//to its category array, and its own index.
marker.data = {
category: arr,
index: j
};
google.maps.event.addListener(marker, 'click', clickMarker);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
See comments in code.

Categories

Resources