Cannot read property '1' of undefined in leaflet.js - javascript

I‘m running a code to plot the marker according to their coordination on leaflet after I getJSON from mysql database,
but the system continue getting error as 'Uncaught TypeError: Cannot read property '1' of undefined'.Code is presented below
<html>
<head>
<title>A Leaflet map</title>
<link rel="stylesheet"
href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="crossorigin=""/>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.10.2.min.js?ver=1.10.2'></script>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript' src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="crossorigin=""></script>
<div id="map"></div>
<style>
#map{ height: 100% }
</style>
</head>
<body>
<script type="text/javascript">
var markerArray = [];
// initialize the map
var map = L.map('map').setView([40.730610, -73.935242], 11.5);
// load a tile layer
L.tileLayer('https://cartodb-basemaps{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',{
attribution: '© <a href=" ">OpenStreetMap</a > © <a href="http://cartodb.com/attributions">CartoDB</a >',
subdomains: 'abcd',
maxZoom: 19
}).addTo(map);
var url= "http://dev.spatialdatacapture.org:8827/airbnb";
console.log(url);
$.getJSON( url, function(data){
$.each(data, function(k,v){
//var latLng = new google.maps.LatLng(v.points.y, v.points.x);
var lng = v.longitude;
var lat = v.latitude;
var marker = {
"type":'Feature',
"properties":
{
"id":v.id,
"host_id":v.host_id,
"host_listings_count":v.host_listings_count,
"property_type":v.property_type,
"room_type":v.room_type,
"price":v.price,
"review_scores_rating":v.review_scores_rating,
"review_scores_accuracy":v.review_scores_accuracy,
"review_scores_cleaness":v.review_scores_cleaness,
"review_scores_checkin":v.review_scores_checkin,
"review_scores_communication":v.review_scores_communication,
"review_scores_location":v.review_scores_location,
"review_scores_value":v.review_scores_value,
"NTACode":v.NTACode,
"NTAName":v.NTAName,
},
"geometry":{
"type":'Point',
"coordination" : [lng,lat]
}
};
markerArray.push(marker);
});
var geoj = {"type":"FeatureCollection","features": markerArray};
console.log(geoj);
L.geoJson(geoj,{
PointToLayer: function(feature,latlng){
returnL.circleMarker(latLng,geojsonMarkerOptions).on('mouseover',function(){
this.bindPopup("NTAName"+feature.properties.NTAName +"</div><div>"+"price"+feature.properties.price+"</div><div>"+"</div>").openPopup();
});
}
}).addTo(map);
});
</script>
</body>
</html>
Then I got error: Cannot read property '1' of undefined in leaflet.js
Does anyone know what should I do?

The GeoJSON format expects the key "coordinates" in geometry of features, instead of "coordination" in your code.
You can easily check the GeoJSON data that you build using online GeoJSON linting tools.
Furthermore you have 2 typos:
PointToLayer option should be pointToLayer (lowercase first letter)
returnL.circleMarker should be return L.circleMarker (whitespace between return return and circleMarker)
If that is not enough to remove the error, we would need more information from your side. Ideally share a reproduction example.

Related

Having troubles libraries=places in google maps api <script>

var map;
var service;
var index = 0;
var posArray = [];
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(init);
});
function init(location) {
enable();
googleMap();
var currentLocation = {lat: location.coords.latitude, lng: location.coords.longitude};
var mapOptions = {
center: currentLocation,
zoom: 10,
mapTypeId: google.maps.MapTypeId.READMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
<link rel="stylesheet" th:href="#{/style.css}"/>
<link rel="stylesheet" th:href="#{/bootstrap.css}"/>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={MY_KEY}&libraries=places"></script>
<script type="text/javascript" th:src="#{/jquery.js}"></script>
<script type="text/javascript" th:src="#{/client.js}"></script>
</head>
I am currently have trouble loading my libraries=places into my google maps api. The api will let me either use the key OR libraries=places but not both. The error shows:
"Exception parsing document: template="index", line 10 - column 134"
line 10 is
script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={MY_KEY}&libraries=places"
column 134 is the "=" between libraries and places.
Any suggestions would be welcome.
Can you try blow is updated;
<script type="text/javascript" th:src="#{https://maps.googleapis.com/maps/api/js(key='MY_KEY',libraries=places)}"></script>
I was able to get it to work with the following code:
<script type="text/javascript" th:src="#{https://maps.googleapis.com/maps/api/js(libraries=places, key=MY_KEY)}"></script>

Linking Google Script Variable to the Javascript in HTML

So I feel I'm almost there to the solution but I'm really in need of help here. What I'm trying to do is to create an array using .getValues() to get a range that contains four columns (Name, Address, Latitude, and Longitude). After that I want to return the variable back into a global variable and then call that variable from the HTML side. I tried linking the google script with the HTML and then calling the variable there but having quite a bit of trouble with that. Thank you guys for all of your help!
Below is the google script:
var id = 'Spreadsheet Key';
function doGet(e) {
var html = HtmlService.createTemplateFromFile('Sample');
return html.evaluate().setTitle('Directory Map');
}
function entries() {
var blop =
SpreadsheetApp.openById(id).getSheetByName('Sheet1').getRange('A1:D').getValues();
return blop;
}
This is the HTML in Google Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.8283, lng: -98.5795},
zoom: 5,
mapTypeId: 'roadmap',
gestureHandling: 'greedy'
});
var locations = [blop];
for (var i = 0; i < locations.length; i++) {
var sites = locations[i];
var myLatLng = new google.maps.LatLng(sites[2],sites[3]);
var sites = new google.maps.Marker({
position: myLatLng,
map: map,
title: sites[0],
});
};
}
</script>
<script> google.script.run.entries(); </script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&libraries=places&callback=initAutocomplete"async defer></script>
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="SampleCode.gs"></script>
</body>
</html>
The starting point is:
<script> google.script.run.entries(); </script>
The above code runs when the page is loaded in the browser. You need a "success handler", and then the success handler can store the data somewhere. You could put the data into a window variable, or local browser storage.
<script>
window.storeSheetValues = function(theReturnedData) {
console.log('theReturnedData: ' + theReturnedData)
console.log('typeof theReturnedData: ' + typeof theReturnedData)
window.mySheetData = theReturnedData;//Put the data into a window variable
}
google.script.run
.withSuccessHandler(storeSheetValues)
.entries();
</script>
Check the data type of the return value coming back from the server. If it's a string, you may want to turn it back into an array.

Passing Variables by Reference in JavaScript

I am trying to display and center a map for the users current location. Everything works fine if I manually enter a hard coded latitude and longitude, but these needs to be dynamic as one user often changes location.
I suspect I am making a basic mistake, but my logic seems like it is correct to me. Please check my work and let me know what I am doing wrong? The line that is remarked out with Latitude and Longitude is the line I want to use instead of the previous line with the hard coded values.
<!DOCTYPE html>
<html>
<head>
<title>W123</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function showlocation() {
navigator.geolocation.getCurrentPosition(getLocation);
}
function getLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
function loadMapScenario() {
var mapOptions = {
credentials: 'My API key code goes here',
center: new Microsoft.Maps.Location(39.1887643719098, -92.8261546188403),
//center: new Microsoft.Maps.Location(latitude, longitude),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 8
};
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), mapOptions);
var urlTemplate = 'http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoom}/{x}/{y}.png';
var timestamps = ['900913-m50m', '900913-m45m', '900913-m40m', '900913-m35m', '900913-m30m', '900913-m25m', '900913-m20m', '900913-m15m', '900913-m10m', '900913-m05m', '900913'];
var tileSources = [];
for (var i = 0; i < timestamps.length; i++) {
var tileSource = new Microsoft.Maps.TileSource({
uriConstructor: urlTemplate.replace('{timestamp}', timestamps[i])
});
tileSources.push(tileSource);
}
var animatedLayer = new Microsoft.Maps.AnimatedTileLayer({ mercator: tileSources, frameRate: 500 });
map.layers.insert(animatedLayer);
}
</script>
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=loadMapScenario' async defer></script>
</body>
</html>
You want to pass in the latitude and longitude into your loadMapScenario function as seen below
function loadMapScenario(latitude,longitude) {
....your code here....
}
Change your callback in the bing map include to a new function like "mapUserLocation" then have mapUserLocation perform the following tasks
function mapUserLocation() {
// code here to get the latitude and longitude from users position
loadMapScenario(latitude,longitude);
}

Google Map markers not showing for locations loaded from database

I am trying to use Google Maps API for my website with Node.js and mongodb. I have an express app on Node.js that fetches locations from mongodb. I have set up the map on my website. However, it is showing markers only for the locations hard coded in the Node.js code. Here, is the piece of code from routes.js
app.get('/website', function(req, res){
website.website(function(events){
res.render('website/index_page.ejs', {events : events});
});
});
The index_page.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<% include map_head %>
</head>
<body>
<h2>Events</h2>
<ol>
<%events.forEach(function(event){%>
<li><p><%= event %></p></li>
<%});%>
</ol>
<div id="googleMap" style="width:650px;height:700px;"></div>`
</body>
</html>`
And the map_head.ejs
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(10, 90),
zoom:4,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
events.forEach(function (event) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(event.latitude), Number(event.longitude)),
map: map,
title: "test"
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The events object is only known to the server and its ejs parser.
The client does not receive the events object in the code you provided.
It only receives an "ol" list.
Your could include the events object in map_head.ejs with code like this:
var events=<%- JSON.stringify(events); %>;

How to load map for specific country by leaflet js

here i got a sample code which shows the same but i like to know from where to arrange the lat lang for any specific country or city.
here map done for London
var london = new L.LatLng(51.505, -0.09);
map.setView(london, 13);
so if some one knows the LatLng for specific country then it is possible. but just tell is there source exist which tell me the latlang for any country or city.
here is full sample code
<html>
<head>
<title>Leaflet Events Example</title>
<link rel="stylesheet" href="leaflet/leaflet.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="leaflet/leaflet.ie.css" /><![endif]-->
<script src="leaflet/leaflet.js"></script>
<script language="javascript">
var map;
var popup = L.popup();
function init() {
map = new L.Map('map');
popup = new L.Popup();
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18
}).addTo(map);
map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text.
var london = new L.LatLng(51.505, -0.09);
map.setView(london, 13);
map.on('click', onMapClick);
}
//Listener function taking an event object
function onMapClick(e) {
//map click event object (e) has latlng property which is a location at which the click occured.
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="map" style="height: 200px"></div> <!-- width equals available horizontal space by default -->
</body>
</html>
Another code
<html>
<head>
<title>Leaflet marker array example</title>
<link rel="stylesheet" href="leaflet/leaflet.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="leaflet/leaflet.ie.css" /><![endif]-->
<script src="leaflet/leaflet.js"></script>
<script language="javascript">
function init() {
var map = new L.Map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18
}).addTo(map);
map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text.
var london = new L.LatLng(51.5056,-0.1213);
map.setView(london, 13);
// Define an array. This could be done in a seperate js file.
// This tidy formatted section could even be generated by a server-side script
// or fetched seperately as a jsonp request.
var markers = [
[ -0.1244324, 51.5006728, "Big Ben" ],
[ -0.119623, 51.503308, "London Eye" ],
[ -0.1279688, 51.5077286, "Nelson's Column<br>wp" ]
];
//Loop through the markers array
for (var i=0; i<markers.length; i++) {
var lon = markers[i][0];
var lat = markers[i][1];
var popupText = markers[i][2];
var markerLocation = new L.LatLng(lat, lon);
var marker = new L.Marker(markerLocation);
map.addLayer(marker);
marker.bindPopup(popupText);
}
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="map" style="height: 200px"></div>
</body>
</html>
thanks
If you just want to know the LatLng of any country or city
For example you want to know the LatLng of Australia, Just type this in google
australia lat long like below
Try Google Geocoding API. With this you can get the LatLng of an address.

Categories