I use the Google Maps & Google Places API the show my business data on a map. Actually the info window opens when i click the map marker but my goal is, that the infowindow opens on page load.
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
/* place.formatted_address + '<br />' + */
place.address_components[1].long_name + ' ' + place.address_components[0].long_name + '<br />' +
place.address_components[6].long_name + ' ' + place.address_components[2].long_name + '<br />' +
place.rating + place.user_ratings_total + '</div>');
infowindow.open(map, this);
});
}
});
You should move the code for info window and marker in main area
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
/* place.formatted_address + '<br />' + */
place.address_components[1].long_name + ' ' + place.address_components[0].long_name + '<br />' +
place.address_components[6].long_name + ' ' + place.address_components[2].long_name + '<br />' +
place.rating + place.user_ratings_total + '</div>');
infowindow.open(map, marker);
Related
I am using Google Maps to plot a number of pins and am having problems hiding empty strings within the info window.
All locations have a name and address but then there are 3 fields which will not necessarily all have a value.
These are:
telephone number
email address
website
var markersOnMap = [{
title: "Location One",
placeName: "Location One",
address: "Address",
telephone: "01234567890",
website: "http://somewebaddress.com",
emailaddress: "",
LatLng: [{
lat: 40.4319077,
lng: 116.5703749
}]
}];
I then put the information into a variable to output it.
var contentString = '<div id="content"><p>' + markersOnMap[i].placeName + '</p><p>' + markersOnMap[i].address + '</p><p>T: ' + markersOnMap[i].telephone + '</p><p>' + markersOnMap[i].website + '</p><p><a href=mailto:"' + markersOnMap[i].emailaddress + '>' + markersOnMap[i].emailaddress + '</a></p></div>';
In the example above, Location One, I would like to hide the email address as it does not have a value.
How do I check if the value of those strings are empty and then not output them on a per location basis.
If anyone can provide any assistance, that would be great.
You could use proper var and ternary operator (or if ) for check each content and set the proper html dinamic string code
aPlaceName = (markersOnMap[i].placeName !='' ? '<p>' + markersOnMap[i].placeName + '</p>' :'');
aAddress = (markersOnMap[i].address !='' ? '<p>' + markersOnMap[i].placeName + '</p>' :'');7
...
and build the contentString using the var
var contentString = '<div id="content">' + aPlaceName + aAddress..... +'</div>';
One option would be to build the contentString incrementally if the pieces exist:
var contentString = '<div id="content">'
if (!!markersOnMap[i].placeName)
contentString += '<p>' + markersOnMap[i].placeName + '</p>';
if (!!markersOnMap[i].address)
contentString += '<p>' + markersOnMap[i].address + '</p>';
if (!!markersOnMap[i].telephone)
contentString += '<p>T: ' + markersOnMap[i].telephone + '</p>';
if (!!markersOnMap[i].website)
contentString += '<p>' + markersOnMap[i].website + '</p>';
if (!!markersOnMap[i].emailaddress)
contentString += '<p><a href=mailto:"' + markersOnMap[i].emailaddress + '>' + markersOnMap[i].emailaddress + '</a></p>';
contentString += '</div>';
proof of concept fiddle
code snippet:
// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
var markersOnMap = [{
title: "Location One",
placeName: "Location One",
address: "Address",
telephone: "01234567890",
website: "http://somewebaddress.com",
emailaddress: "",
LatLng: [{
lat: 40.4319077,
lng: 116.5703749
}]
},
{
title: "Location Two",
placeName: "Location Two",
address: "Address2",
emailaddress: "",
LatLng: [{
lat: 40.432,
lng: 116.58
}]
}
];
function initMap() {
var uluru = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersOnMap.length; i++) {
var marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map
});
bounds.extend(marker.getPosition());
marker.addListener('click', (function(i) {
return function(evt) {
var contentString = '<div id="content">'
if (!!markersOnMap[i].placeName)
contentString += '<p>' + markersOnMap[i].placeName + '</p>';
if (!!markersOnMap[i].address)
contentString += '<p>' + markersOnMap[i].address + '</p>';
if (!!markersOnMap[i].telephone)
contentString += '<p>T: ' + markersOnMap[i].telephone + '</p>';
if (!!markersOnMap[i].website)
contentString += '<p>' + markersOnMap[i].website + '</p>';
if (!!markersOnMap[i].emailaddress)
contentString += '<p><a href=mailto:"' + markersOnMap[i].emailaddress + '>' + markersOnMap[i].emailaddress + '</a></p>';
contentString += '</div>';
infoWindow.setContent(contentString);
infoWindow.open(map, this);
}
})(i))
}
map.fitBounds(bounds);
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>' +
'<div id="bodyContent">' +
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
'sandstone rock formation in the southern part of the ' +
'Northern Territory, central Australia. It lies 335 km (208 mi) ' +
'south west of the nearest large town, Alice Springs; 450 km ' +
'(280 mi) by road. Kata Tjuta and Uluru are the two major ' +
'features of the Uluru - Kata Tjuta National Park. Uluru is ' +
'sacred to the Pitjantjatjara and Yankunytjatjara, the ' +
'Aboriginal people of the area. It has many springs, waterholes, ' +
'rock caves and ancient paintings. Uluru is listed as a World ' +
'Heritage Site.</p>' +
'<p>Attribution: Uluru, <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">' +
'https://en.wikipedia.org/w/index.php?title=Uluru</a> ' +
'(last visited June 22, 2009).</p>' +
'</div>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Ayers Rock)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
I mapped some objects and I created info-window using the following script:
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
info: '<h3 style="color:brown">' + ThName + '</h3>' +
'<img src = "' + photo1 + '" style="width:200px;height:150px; vertical-align:top;margin-right:.5em"/>' +
'<img src = "' + photo2 + '" style="width:200px;height:150px; vertical-align:top"/>' +
'<br/> ' + cap1 + ' ' + cap2
});
How can I put the captions cap1 under photo1 and cap2 under photo2?
My intial thought is to create a table with two columns and two rows but I do not know how.
I am using Google Maps API for my current project and used info-window for the same purpose. You can use it in a similar way if you like:
var contentString = '<h3 style="color:brown">' + ThName + '</h3>' +
'<figure>'+ '<img src = "' + photo1 +
'"style="width:200px;height:150px; vertical-
align:top;margin-right:.5em"/>' +
'<figcaption>'+ cap1 + '</figcaption>' +
'</figure>' + '<figure>'+ '<img src = "' + photo2 +
'"style="width:200px;height:150px; vertical-
align:top;"/>' +'<figcaption>'+ cap2 +
'</figcaption>' + '</figure>';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
content: contentString
});
For captions, I used figure and figcaption tags.
I am using JavaScript in HTML page to display GPS locations with markers and all these GPS locations are connected
I am trying to implement a map/direction based application using Google maps V3 API. So far I have been able to display the map and show directions for two locations selected. the first one is my current location , the second one is the location of costumer (his/her information exist in my database). All the markers are being displayed in the output properly.
To get directions to a location specified by coordinates, make it a google.maps.LatLng object. To get that from your data in the select, save the coordinates as a string in the value, then parse out the latitude and longitude to create the LatLng object.
save the coordinates in the option value:
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
parse those coordinates and create a google.maps.LatLng object in the directions request:
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
// ....
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));
// Detect user location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});
}, function() {
alert('Geolocation is supported, but it failed');
});
}
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/eca59a21899fe19b1f556ff033a33dff2a6bdd0c/get_data_google_api', function(data) {
var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
});
}
function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';
if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 18px;
}
#sidebar {
float: right;
width: 30%;
}
#main {
padding-right: 15px;
}
.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="init();">
<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="afficher la direction" onclick="calculateRoute();" />
</form>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>
</body>
Let me explain the project a bit. i have a huge list of stores with addresses (longitude and latitude and code client ....).
Now, my problem is, i must be able to filter these markers depending on CodeClient i mean to find the client in google maps based on CodeClient .
The implementation is similar to the answer I mentioned before. You should add an input for code of client and a search button. In the function where you create markers add a property 'code' for each marker marker.code = CodeClient;. When you click search button it executes the filterByCode() function. If you pass empty value it restores all markers.
Have a look at modified code
// necessary variables
var map;
var infoWindow;
var markersData = [];
var markerCluster;
var markerArray = []; //create a global array to store markers
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(32, -6),
zoom: 7,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// create MarkerClusterer, markersArray is not populated yet
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// a new Info Window is created
infoWindow = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
// Finally displayMarkers() function is called to begin the markers creation
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers() {
// this variable sets the map bounds according to markers position
var bounds = new google.maps.LatLngBounds();
// for loop traverses markersData array calling createMarker function for each marker
$.get("https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/bae93c852669a35f0e7053e9f8d068841ddf146a/get_data_google_api", function(response) {
markersData = JSON.parse(response);
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].Latitude, markersData[i].Longitude);
var Route = markersData[i].Route;
var Secteur = markersData[i].Secteur;
var Agence = markersData[i].Agence;
var CodeClient = markersData[i].CodeClient;
var PrecisionGPS = markersData[i].PrecisionGPS;
var Latitude = markersData[i].Latitude;
var Longitude = markersData[i].Longitude;
var BarCode = markersData[i].BarCode;
var PrenomClient = markersData[i].PrenomClient;
var NumAdresse = markersData[i].NumAdresse;
var Tel = markersData[i].Tel;
var Whatsapp = markersData[i].Whatsapp;
var NbrFrigo = markersData[i].NbrFrigo;
var OpenAm = markersData[i].OpenAm;
var CloseAm = markersData[i].CloseAm;
var OpenPm = markersData[i].OpenPm;
var ClosePm = markersData[i].ClosePm;
var OpenAmVen = markersData[i].OpenAmVen;
var CloseAmVen = markersData[i].CloseAmVen;
var OpenPmVen = markersData[i].OpenPmVen;
var ClosePmVen = markersData[i].ClosePmVen;
var OpenAmDim = markersData[i].OpenAmDim;
var CloseAmDim = markersData[i].CloseAmDim;
var OpenPmDim = markersData[i].OpenPmDim;
var ClosePmDim = markersData[i].ClosePmDim;
var IMEI = markersData[i].IMEI;
var Date_Added = markersData[i].Date_Added;
createMarker(latlng, Route, Agence, Secteur, CodeClient, PrecisionGPS, Latitude, Longitude, BarCode, PrenomClient, NumAdresse, Tel, Whatsapp, NbrFrigo, OpenAm, CloseAm, OpenPm, ClosePm, OpenAmVen, CloseAmVen, OpenPmVen, ClosePmVen, OpenAmDim, CloseAmDim, OpenPmDim, ClosePmDim, IMEI, Date_Added);
// marker position is added to bounds variable
bounds.extend(latlng);
}
// Finally the bounds variable is used to set the map bounds
// with fitBounds() function
map.fitBounds(bounds);
});
}
// This function creates each marker and it sets their Info Window content
function createMarker(latlng, Route, Agence, Secteur, CodeClient, PrecisionGPS, Latitude, Longitude, BarCode, PrenomClient, NumAdresse, Tel, Whatsapp, NbrFrigo, OpenAm, CloseAm, OpenPm, ClosePm, OpenAmVen, CloseAmVen, OpenPmVen, ClosePmVen, OpenAmDim, CloseAmDim, OpenPmDim, ClosePmDim, IMEI, Date_Added) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: CodeClient
});
marker.code = CodeClient;
markerArray.push(marker); //push local var marker into global array
// add marker to the MarkerClusterer
markerCluster.addMarker(marker);
// This event expects a click on a marker
// When this event is fired the Info Window content is created
// and the Info Window is opened.
google.maps.event.addListener(marker, 'click', function() {
var dicoFrigosDetails = {};
var HTMLtext = "";
for (var i = 1; i <= Object.keys(dicoFrigosDetails).length / 4; i++) {
HTMLtext += '';
}
// Creating the content to be inserted in the infowindow
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">Code Client : ' + CodeClient +
'</div>' + '<div class="iw_content">Précision : ' + PrecisionGPS +
'<br />Latitude : ' + Latitude +
'<br />Longitude : ' + Longitude +
'<br />Route : ' + Route +
'<br />Secteur : ' + Secteur +
'<br />Agence : ' + Agence +
'<br />Code-barres : ' + BarCode +
'<br />prenom de Client : ' + PrenomClient +
//'<br />nom Complet de Client : ' + PrenomClient + ' ' + NomClient +
'<br />Num Adresse : ' + NumAdresse +
'<br />Téléphone : ' + Tel +
'<br />Whatsapp : ' + Whatsapp +
'<br />Nbr Frigos : ' + NbrFrigo + HTMLtext +
'<br />Ouverture Matin : ' + OpenAm +
'<br />Fermeture Matin : ' + CloseAm +
'<br />Ouverture après-midi : ' + OpenPm +
'<br />Fermeture Après-midi : ' + ClosePm +
'<br />Ouverture Matin Ven : ' + OpenAmVen +
'<br />Fermeture Matin Ven : ' + CloseAmVen +
'<br />Ouverture après-midi Ven: ' + OpenPmVen +
'<br />Fermeture après-midi Ven: ' + ClosePmVen +
'<br />Ouverture Matin Dim : ' + OpenAmDim +
'<br />Fermeture Matin Dim : ' + CloseAmDim +
'<br />Ouverture après-midi Dim : ' + OpenPmDim +
'<br />Fermeture après-midi Dim : ' + ClosePmDim +
'<br />IMEI : ' + IMEI +
'<br />Date Passage : ' + Date_Added +
'</div>';
// including content to the Info Window.
infoWindow.setContent(iwContent);
// opening the Info Window in the current map and at the current marker location.
infoWindow.open(map, marker);
});
}
function filterByCode() {
var code = document.getElementById("code-client").value;
var bounds = new google.maps.LatLngBounds();
markerCluster.clearMarkers();
if (code) {
markerArray.forEach(function(marker) {
marker.setMap(null);
});
var filtered = markerArray.filter(function(marker) {
return marker.code === code;
});
if (filtered && filtered.length) {
filtered.forEach(function(marker) {
bounds.extend(marker.getPosition());
marker.setMap(map);
});
markerCluster.addMarkers(filtered);
markerCluster.redraw();
map.fitBounds(bounds);
}
} else {
markerArray.forEach(function(marker) {
bounds.extend(marker.getPosition());
marker.setMap(map);
});
markerCluster.addMarkers(markerArray);
markerCluster.redraw();
map.fitBounds(bounds);
}
}
html {
height: 100%;
background: gray;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>InnoTech - Map - Server</title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="search-code-container">
<input id="code-client" title="Enter code" type="text" placeholder="Enter code (E.g. 511557)" value=""/>
<input id="code-client-btn" type="button" value="Search" onclick="filterByCode()" />
</div>
<div id="map-canvas" />
I hope this helps!
I have two listeners, one for user clicks and one for "insert_at". I want to implement a self-completion polygon. So initially the user will click to draw a polygon. When the user is drawing the polygon, I don't want to trigger the "insert_at" listener. After the polygon is completed, I want the "insert_at" listener to be triggered. How do I do that? My code snippets below:
var poly;
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: 3.165236, lng: 101.654315} //choose an appropriate center for the map
});
poly = new google.maps.Polygon({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3,
editable: true
});
poly.setMap(map);
map.addListener('click', addLatLng);
google.maps.event.addListener(poly.getPath(), 'insert_at', function(index, obj) {
var path = poly.getPath();
//Only insert if it's not the last coordinate
if ($("#polygon-coordinates").find("div.nested-fields ").eq(index).length > 0) {
$("#polygon-coordinates").find("div.nested-fields").eq(index - 1).after('<div class="nested-fields row"></br><div class="col-xs-6"></br><label>Latitude</label></br><input class="form-control" id=""area[polygon_coordinates_attributes][' + index + '][latitude]" name="area[polygon_coordinates_attributes][' + index + '][latitude]" value="' + path.b[index].lat() + '"></div>' +
'<div class="col-xs-6"></br><label>Longitude</label></br><input class="form-control" name="area[polygon_coordinates_attributes][' + index + '][longitude]" name="area[polygon_coordinates_attributes][' + index + '][longitude]" value="' + path.b[index].lng() + '"></div></br></div>');
addMarker(path.b[index], index);
}
});
google.maps.event.addListener(poly.getPath(), 'set_at', function(index, obj) {
var path = poly.getPath();
var lat = "area[polygon_coordinates_attributes][" + index + "][latitude]";
var lng = "area[polygon_coordinates_attributes][" + index + "][longitude]";
$("input[name='" + lat + "']").val(path.b[index].lat());
$("input[name='" + lng + "']").val(path.b[index].lng());
//delete existing marker here
deleteMarker(index);
debugger
addMarker(path.b[index], index);
});
}
function isNotDupMarker(path, index) {
//check if the coordinates are duplicated
if (markers[index - 1] !== undefined && path[index].lat() !== markers[index - 1].position.lat()) {
return true;
} else {
return false;
}
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
markers.push(marker);
}
function deleteMarker(index) {
markers[index].setMap(null);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
var index = path.push(event.latLng);
var i = index - 1
addMarker(event.latLng, index);
$("#polygon-coordinates").append('<div class="nested-fields row"></br><div class="col-xs-6"></br><label>Latitude</label></br><input class="form-control" id=""area[polygon_coordinates_attributes][' + i + '][latitude]" name="area[polygon_coordinates_attributes][' + i + '][latitude]" value="' + path.getAt(index - 1).lat() + '"></div>' +
'<div class="col-xs-6"></br><label>Longitude</label></br><input class="form-control" name="area[polygon_coordinates_attributes][' + i + '][longitude]" name="area[polygon_coordinates_attributes][' + i + '][longitude]" value="' + path.getAt(index - 1).lng() + '"></div></br></div>');
}