update I
Based on feedback, I've changed var maps to var adds.
problem description
I'm working on Rails 3.0.0.beta2, following Advanced Rails Recipes "Recipe #32, Mark locations on a Google Map" and I hit a road block: I do not see a google map. My #adds view uses #adds.to_json to connect the google maps api with my model. My database contains "latitude" "longitude", as floating points. And the entire project can be accessed at github.
Can you see where I'm not connecting the to_json output with the javascript correctly? Can you see other glairing errors in my javascript? Thanks in advance!
My application.js file:
function initialize() {
if (GBrowserIsCompatible() && typeof adds != 'undefined') {
var adds = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.addControl(new GLargeMapControl());
function createMarker(latlng, add) {
var marker = new GMarker(latlng);
var html="<strong>"+add.first_name+"</strong><br />"+add.address;
GEvent.addListener(marker,"click", function() {
map.openInfoWindowHtml(latlng, html);
});
return marker;
}
var bounds = new GLatLngBounds;
for (var i = 0; i < adds.length; i++) {
var latlng=new GLatLng(adds[i].latitude,adds[i].longitude)
bounds.extend(latlng);
map.addOverlay(createMarker(latlng, adds[i]));
}
map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
}
}
window.onload=initialize;
window.onunload=GUnload;
Layouts/adds.html.erb:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true_or_false&key=ABQIAAAAeH4ThRuftWNHlwYdvcK1QBTJQa0g3IQ9GZqIMmInSLzwtGDKaBQvZChl_y5OHf0juslJRNx7TbxK3Q" type="text/javascript"></script>
<% if #adds -%>
<script type="text/javascript">
var adds = <%= raw #adds.to_json %>;
</script>
<% end -%>
Rails Console Output
a = Add.all
=> [#<Add id: 1, first_name: "Jason", last_name: "Wade", address: "225 Anzavista Ave, San Francisco, CA", address2: "", zip: "94115", city: "San Francisco", phone: "415-280-6678", float: nil, campaign_id: 1, email: "jwade#gmail.com", employer: "Google", occupation: "", created_at: "2010-04-06 14:00:36", updated_at: "2010-04-06 14:00:36", latitude: 37.779623, longitude: -122.445662>]
ruby-1.9.1-p378 > a.to_json
=> "[{\"address\":\"225 Anzavista Ave, San Francisco, CA\",\"address2\":\"\",\"campaign_id\":1,\"city\":\"San Francisco\",\"created_at\":\"2010-04-06T14:00:36Z\",\"email\":\"jwade#gmail.com\",\"employer\":\"Google\",\"first_name\":\"Jason\",\"float\":null,\"id\":1,\"last_name\":\"Wade\",\"latitude\":37.779623,\"longitude\":-122.445662,\"occupation\":\"\",\"phone\":\"415-280-6678\",\"updated_at\":\"2010-04-06T14:00:36Z\",\"zip\":\"94115\"}]"
var bounds = new GLatLngBounds;
should be
var bounds = new GLatLngBounds();
And you were initially correct:
var map = new GMap2(document.getElementById("map"));
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Looking to clear all marker clusters using on click from a floating panel. I can clear and show all markers but not the marker clustered icons. I have scoured through multiple similar questions but am missing something for sure.
When I try to use the below code it comes back with markerCluster is not defined at clearMarkers.
JS Code:
var map;
var geocoder;
var markerAll;
var markers = [];
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {lat: 42.181613, lng: -73.215013};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: monterey,
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
showSearchedCustomer(searchData);
}
function showAllCustomers(allData) {
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
//Create marker clusterer to group data
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'images/m'
});
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
// var img = document.createElement('img');
// img.src = 'images/santahat.png';
// img.style.width = '50px';
// content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var markerAll = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
icon: iconBase + 'homegardenbusiness.png'
});
//push markers to marker clusterer
markerCluster.addMarker(markerAll);
markers.push(markerAll);
})
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
markerCluster.clearMarkers(markerAll); <----- THIS IS WHAT I TRIED TO ADD TO CLEAR CLUSTERS
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
You need to put the markerCluster in the global scope so it can be used in the clearMarkers function (which is (probably) defined in the the global scope).
var markerCluster;
function showAllCustomers(allData) {
//Create marker clusterer to group data
markerCluster = new MarkerClusterer(map, [], {
imagePath:
"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
});
proof of concept fiddle
code snippet:
var map;
var geocoder;
var markerAll;
var markers = [];
//Code to load the map with center point of Monterey MA
function initMap() {
var monterey = {
lat: 42.181613,
lng: -73.215013
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -28.024,
lng: 140.887
},
mapTypeId: google.maps.MapTypeId.HYBRID,
labels: true,
});
//collect customer data and geocoder object - declare geocoder as global
var cusdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
// codeAddress(cusdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
allData = locations;
showAllCustomers(allData);
var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
// searchData = locations;
// showSearchedCustomer(searchData);
}
var markerCluster;
function showAllCustomers(allData) {
//Create marker clusterer to group data
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://unpkg.com/#google/markerclustererplus#4.0.1/images/m',
});
//declare info window variable outside of loop to allow to clear when selecting other markers
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data) {
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = [data.lastName + ' ' + data.physicalAddress];
content.appendChild(strong);
//add image to infowindow - you are also able to add image path to mysql and then append dynamically
// var img = document.createElement('img');
// img.src = 'images/santahat.png';
// img.style.width = '50px';
// content.appendChild(img);
//Create markers for customer locations and customize
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var markerAll = new google.maps.Marker({
position: new google.maps.LatLng(data.latitude, data.longitude),
map: map,
// icon: iconBase + 'homegardenbusiness.png'
});
//push markers to marker clusterer
markerCluster.addMarker(markerAll);
markers.push(markerAll);
})
google.maps.event.addDomListener(document.getElementById('btn'), 'click', clearMarkers);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
markerCluster.clearMarkers(markerAll);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
const locations = [{
latitude: -31.56391,
longitude: 147.154312,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.718234,
longitude: 150.363181,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.727111,
longitude: 150.371124,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.848588,
longitude: 151.209834,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -33.851702,
longitude: 151.216968,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -34.671264,
longitude: 150.863657,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -35.304724,
longitude: 148.662905,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -36.817685,
longitude: 175.699196,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -36.828611,
longitude: 175.790222,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.75,
longitude: 145.116667,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.759859,
longitude: 145.128708,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.765015,
longitude: 145.133858,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.770104,
longitude: 145.143299,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.7737,
longitude: 145.145187,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.774785,
longitude: 145.137978,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -37.819616,
longitude: 144.968119,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -38.330766,
longitude: 144.695692,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -39.927193,
longitude: 175.053218,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -41.330162,
longitude: 174.865694,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -42.734358,
longitude: 147.439506,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -42.734358,
longitude: 147.501315,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -42.735258,
longitude: 147.438,
lastName: "Smith",
physicalAddress: "New York, NY"
},
{
latitude: -43.999792,
longitude: 170.463352,
lastName: "Smith",
physicalAddress: "New York, NY"
},
];
/* 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;
}
<!DOCTYPE html>
<html>
<head>
<title>Marker Clustering</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="btn" type="button" value="Clear Markers" />
<div id="map"></div>
<div id="data">[]</div>
<div id="allData">[]</div>
<div id="searchData">[]</div>
</body>
</html>
I am working on analyzing homes for sale and trying to make them from and object. I've tried modifying the code with solutions from other posts, such as: correcting zoom, coordinates, etc. without any success. Hoping someone can figure this out since I've been at it for over a week.
I am working on a Google Appscript WebApp so I'm not sure if this is causing the errors.
HTML
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<base target="_top">
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCoV68jYgCZRuOSao1VFcTJbAW4py7yycs&callback=displayMap"></script>
</head>
<body>
<div class= "map" id="map-display">
</body>
</html>
CSS
.map{
height: 400px;
width: 100%;
display: none; //initially hidden until the displayMap() function runs
}
Javascript
// other javascript code goes here that produces the `match` results in the next function
document.getElementById("analysis").addEventListener("click", displayMap); //when a table is clicked, then the map is meant to be displayed
var mapDisplay = document.getElementById("map-display");
let map;
function displayMap(){
var match = {
address: "2126 Daly St"
baths: 1
beds: 2
built: 1910
city: "Los Angeles"
lat: 34.0702443
lon: -118.2152669
lotSize: 3920
mls: 820000258
price: 410000
ref: 573
state: "CA"
status: "Active"
url: "http://www.redfin.com/CA/Los-Angeles/2126-Daly-St-90031/home/6945566"
zip: 90031
}
var compsList = [
{address: "2315 Hancock St"
baths: 2
beds: 3
city: "Los Angeles"
lat: 34.0724244
lon: -118.2093106
lotSize: 5500
mls: "RS20015393"
price: 680000
ref: 1505
saleType: "PAST SALE"
sf: 1169
soldDate: "Thu Feb 20 2020 16:00:00 GMT-0800 (Pacific Standard Time)"
state: "CA"
status: "Sold"
url: "http://www.redfin.com/CA/Los-Angeles/2315-Hancock-St-90031/home/6946949"
zip: 90031
},
{address: "2333 Hancock St"
baths: 2
beds: 3
city: "Los Angeles"
lat: 34.0724248
lon: -118.2093112
lotSize: 5700
mls: "RS20015394"
price: 640000
ref: 1510
saleType: "PAST SALE"
sf: 1171
soldDate: "Thu Feb 2 2020 16:00:00 GMT-0800 (Pacific Standard Time)"
state: "CA"
status: "Sold"
url: "http://www.redfin.com/CA/Los-Angeles/2333-Hancock-St-90031/home/6946949"
zip: 90031
}
];
var compIcon = "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
var options = {
zoom: 8,
center: {lat: match.lat, lng: match.lon},
mapTypeId: "roadmap"
}
map = new google.maps.Map(mapDisplay, options);
var active = {
coords: {lat: match.lat, lng: match.lon},
content: "<h2><a href='"+match.url+"' target='_blank'>"+match.address+"</a></h2>"
}
addMarkers(active) //function should center the map around active and place the "compList" items with a beachflag
var comps = compsList.map(function(c){ //function changes the array to keep only the key/objects needed for the map
var reformat = {
coords: {lat: c.lat, lng: c.lon},
content: "<h2><a href="+c.url+" target='_blank'>"+c.address+" ("+c.distance+" miles away)</a></h2>",
icon: compIcon
}
return reformat
}).forEach(function(r){ addMarkers(r) }) //send each of the two beach flags to be displayed on map along with the center
mapDisplay.style.display = "inline-block";
}
function addMarkers(props){
var marker = new google.maps.Marker({
position: props.coords,
map: map
})
if(props.icon){
marker.setIcon(props.icon)
}
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener("click",function(){
infoWindow.open(map,marker);
})
}
I've tried renaiming the keys from center, position, content to setCenter, setPosition, setContent when I got an error on console but I don't think that's right so I've changed to how the Google documentation has it.
I've tried changing the size of the div and overflow:display but nothing. Any other ideas that can help me get this going? No errors show up on my console so I'm not getting any feedback from Google Maps API....
#haby22. As mentioned in my comments above, in your options you have 'enter' instead of 'center'. You also have 'lgn' instead of 'lng' for longitude in your center settings, and also in your coords.
I also noticed that your match and comp objects were missing commas, so I added them to my example.
I also read that you can pass latitude and longitude as a string then convert to parse to float. So I have done that also.
I commented out your var comps = match.comps.map function because I do not see the code for comps.
EDIT I added this code back based on feedback just for future reference and to follow Bill & Ted's code of excellence. ;)
I also do not have the code you click on so I added an H2 that you can click for the map to appear.
Not sure if this is what you are looking for but here goes nothing:
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<base target="_top">
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCoV68jYgCZRuOSao1VFcTJbAW4py7yycs"></script>
<style>
.map{
height: 400px;
width: 100%;
display: none;
/* initially hidden until the displayMap() function runs */
}
</style>
</head>
<body>
<h2 id="analysis">Display</h2>
<div class= "map" id="map-display"></div>
<script>
// other javascript code goes here that produces the `match` results in the next function
document.getElementById("analysis").addEventListener("click", displayMap); //when a table is clicked, then the map is meant to be displayed
let mapDisplay = document.getElementById("map-display");
let map;
function displayMap(){
var match = {
address: "2126 Daly St",
baths: 1,
beds: 2,
built: 1910,
city: "Los Angeles",
lat: "34.0702443",
lon: "-118.2152669",
lotSize: 3920,
mls: 820000258,
price: 410000,
ref: 573,
state: "CA",
status: "Active",
url: "http://www.redfin.com/CA/Los-Angeles/2126-Daly-St-90031/home/6945566",
zip: 90031,
}
var compsList = [
{address: "2315 Hancock St",
baths: 2,
beds: 3,
city: "Los Angeles",
lat: "34.0724244",
lon: "-118.2093106",
lotSize: 5500,
mls: "RS20015393",
price: 680000,
ref: 1505,
saleType: "PAST SALE",
sf: 1169,
soldDate: "Thu Feb 20 2020 16:00:00 GMT-0800 (Pacific Standard Time)",
state: "CA",
status: "Sold",
url: "http://www.redfin.com/CA/Los-Angeles/2315-Hancock-St-90031/home/6946949",
zip: 90031,
},
{address: "2333 Hancock St",
baths: 2,
beds: 3,
city: "Los Angeles",
lat: "34.0724248",
lon: "-118.2093112",
lotSize: 5700,
mls: "RS20015394",
price: 640000,
ref: 1510,
saleType: "PAST SALE",
sf: 1171,
soldDate: "Thu Feb 2 2020 16:00:00 GMT-0800 (Pacific Standard Time)",
state: "CA",
status: "Sold",
url: "http://www.redfin.com/CA/Los-Angeles/2333-Hancock-St-90031/home/6946949",
zip: 90031,
}
];
var compIcon = "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
var options = {
zoom: 8,
center: {lat: parseFloat(match.lat), lng: parseFloat(match.lon)},
mapTypeId: "roadmap"
}
map = new google.maps.Map(mapDisplay, options);
var active = {
coords: {lat: parseFloat(match.lat), lng: parseFloat(match.lon)},
content: "<h2><a href='"+match.url+"' target='_blank'>"+match.address+"</a></h2>"
}
addMarkers(active) //function should center the map around active and place the "compList" items with a beachflag
var comps = compsList.map(function(c){ //function changes the array to keep only the key/objects needed for the map
var reformat = {
coords: {lat: parseFloat(c.lat), lng: parseFloat(c.lon)},
content: "<h2><a href="+c.url+" target='_blank'>"+c.address+" ("+c.distance+" miles away)</a></h2>",
icon: compIcon
}
return reformat
}).forEach(function(r){ addMarkers(r) }) //send each of the two beach flags to be displayed on map along with the center
mapDisplay.style.display = "inline-block";
}
function addMarkers(props){
var marker = new google.maps.Marker({
position: props.coords,
map: map
})
if(props.icon){
marker.setIcon(props.icon)
}
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener("click",function(){
infoWindow.open(map,marker);
})
}
}
</script>
</body>
</html>
I'm new to javascript. i'm having difficulty printing the data from the location ObservableArray. The data - bind works and i could list out the data from the location ObservableArray at the view but can't print it out on the console. i have been on it for hours now, any help would be appreciated. thank you
Here is the ViewModel
let MapViewModel = function() {
let map
let geocoder;
let self = this;
self.location = ko.observableArray([]);
for (let i = 0; i < locationList.length; ++i) {
self.location.push(new Location(locationList[i]));
}
console.log(this.location()); // Location, Location, Location, Location, Location, Location, Location]
console.log(this.location()[0].name); // Location {name: ƒ, address: ƒ} ...
console.log(this.location().length); //length is 7
}
let Location = function(data) {
this.name = ko.observable(data.name);
this.address = ko.observable(data.address);
}
ko.applyBindings(new MapViewModel());
Here is the Binding Code`
<div class="menu_item_container">
<h1>Neighborhood Map</h1>
<input type="text" id="search" data-bind= 'value:filterLocations, valueUpdate: 'afterKeyDown',value:filterLocations' placeholder="Search Locations...">
<hr>
<nav id=nav>
<ul data-bind='foreach:location'>
<li data-bind="text:name"></li>
</ul>
</nav>
</div>
LocationList
let locationList = [{
name: 'Brooklyn Museum',
address: '200 Eastern Pkwy, Brooklyn, NY 11238'
}, {
name: 'Empire State Building',
address: '350 5th Ave, New York, NY 10118'
}, {
name: 'Statue of liberty',
address: 'New York, NY 10004'
}, {
name: 'Rockefeller Center',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'Brooklyn Bridge',
address: 'Brooklyn Bridge, New York, NY 10038'
},
{
name: 'Time Square',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'World Trade Center',
address: '285 Fulton St, New York, NY 10007'
},
];
This can unwrap observable to regular js and convert this to single string (if needed) and then u can print it console :
let locationsJSON = ko.toJS(self.location);
let locationsString = JSON.stringify(locationsJSON);
I have a AngularJS app where I have an array defined that has a group of dealers. Something like this:
$scope.dealers = [{
name: "Dealer Name",
address: "Address goes here",
website:"site.com",
lat: "latitude",
lng: "longitude"
territory: ['County1', 'County2', 'County3']
},
{
name: "Dealer Name",
address: "Address goes here",
website:"site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
];
A user will input their zip code, and then using the Google Geocode API, I convert their zip code to lat/long coordinates and find their closest dealer based off of coordinates between them, and all of the dealers.
That is working fine.
Here is where I need help. Each dealer has a territory (in the array as counties) that needs to be checked first, before finding the closest dealer, because some dealers have counties in their territories that are actually geographically closer to another dealer.
I have a var that stores the users County based on their zip. So I need to make an IF statement that checks the userZip variable against the dealers array to see if that county exists anywhere in the array. If it does, then I need to return the name of that dealer. If it does not, I will have an ELSE statement that just runs the function I already have, which will just find the closest dealer to their location.
You can use Array.prototype.find()
let dealers = [{
name: "Dealer Name",
address: "Address goes here",
website: "site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
{
name: "Dealer Name",
address: "Address goes here",
website: "site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
];
let country = 'County2';
let found = dealers.find(d => d.territory.includes(country));
if(found)
console.log(found);
else
console.log("..find closest...");
//another case
country = 'NotAnywhere';
found = dealers.find(d => d.territory.includes(country));
if(found)
console.log(found);
else
console.log("..find closest...");
In openstreetmap I'm using openlayer3 to display some data information about random building. It's a simple interaction, when you click on marker data will be presented.
I'm not good in JavaScript so I had some help, and after a while a set up everything like this, you can check it in this JSFIDDLE example.
So, I'm using ol.Feature.html#on to bind event to markers, and I'm loading data with info.innerHTML = "<h1>"+data.name+"</h1>", and everything is looking like this:
/* Create the map */
// setting up coordinates for map to display
var infobox = document.getElementById("info");
var city = ol.proj.transform([-73.920935,40.780229], 'EPSG:4326', 'EPSG:3857');
// setting up openlayer3 view
var view = new ol.View({
center: city,
zoom: 13
});
// Create the map
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: view
});
var Data =
[ { name: "foo",
address: "Some Random Address 1"
, longlat: [-73.927870, 40.763633]
}
, { name: "foo2",
address: "Some Random Address 2"
, longlat: [-73.917356, 40.763958]
}
, { name: "foo3",
address: "Some Random Address 3"
, longlat: [-73.915530, 40.779665]
}
, { name: "foo4",
address: "Some Random Address 4"
, longlat: [-73.916045, 40.779372]
}
, { name: "foo5",
address: "Some Random Address 5"
, longlat: [-73.919682, 40.777365]
}
, { name: "foo6",
address: "Some Random Address 6"
, longlat: [-73.908980, 40.776013]
}
];
function buildFeature(data) {
return new ol.Feature(
{ geometry: new ol.geom.Point(ol.proj.fromLonLat(data.longlat))
, data: data
}
);
}
function curryclickonmarker(element) {
return function (event) {
return clickOnMarker(element, event);
}
}
function clickOnMarker(info, event) {
// This is ugly!
var marker = event.selected[0];
var data = marker.G.data;
// Feed data into DOM
info.innerHTML = "<h1>"+data.name+"</h1>";
}
var selectClick = new ol.interaction.Select();
selectClick.on("select", curryclickonmarker(infobox));
// Setup markers
var features = Data.map(buildFeature);
var markers = new ol.layer.Vector({
tittle: 'City Apratments',
source: new ol.source.Vector({
features: features
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixel',
opacity: 0.75,
src: 'http://openlayers.org/en/v3.12.1/examples/data/icon.png',
})
})
});
map.addLayer(markers);
map.addInteraction(selectClick);
I would like to make this look better, it's looking very ugly, so I need someone to explain to me how can I pass multiple data for the marker, because currently I can only see foo, foo1, foo2, foo3, etc, I'm using openlayers3 API for event's, but can I use pure javascript for this so I can pass addres, pictures, description for the specific marked building, because I need to display a loot, I'm just having hard time understanding how to use javascript to pass more data?