How to load map for specific country by leaflet js - javascript

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.

Related

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

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.

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);
}

how to get variable in javascript and put it to get geolocation in here map?

Can anyone solve this code?
i have some javascript code geolocation and here map script, i want to put geolocation coordinate in here map script..
here bellow my code..
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="http://js.api.here.com/v3/3.0.12.2/mapsjs-ui.css" />
<script src="http://js.api.here.com/v3/3.0.12.2/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0.12.2/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0.12.2/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0.12.2/mapsjs-pano.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0.12.2/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<button onclick="getLocation()">My Location</button><br/>
<input type="text" id="latpos" name="latpos">
<input type="text" id="longpos" name="longpos">
<div id="map" style="width: 100%; height: 400px; background: grey" />
<script type="text/javascript" charset="UTF-8" >
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var origlat= position.coords.latitude ;
var origlong= position.coords.longitude ;
var lat=document.getElementById("latpos");
lat.value=origlat;
var lon=document.getElementById("longpos");
lon.value=origlong;
}
function addMarkerAndSetViewBounds(map) {
var latitu="-6.811408423530006";
var longitu= "110.85068956017494";
var origl= origlat;
var origlo= origlong;
var Isone = new H.map.Marker({lat:latitu, lng:longitu}),
geol = new H.map.Marker({lat:origl, lng:origlo}),
group = new H.map.Group();
group.addObjects([Isone , geol]);
map.addObject(group);
// get geo bounding box for the group and set it to the map
map.setViewBounds(group.getBounds());
}
/Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useCIT: false,
});
var defaultLayers = platform.createDefaultLayers();
//Step 2: initialize a map - this map is centered over Europe
var map = new H.Map(document.getElementById('map'),
defaultLayers.normal.map,{
center: {lat:50, lng:5},
zoom: 15
});
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Create the default UI components
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Now use the map as required...
addMarkerAndSetViewBounds(map);
</script>
</body>
</html>
but, that code didn't work fine..
how to get value var origlat and var origlong in variable var origl and var origlo?
can anyone help me to fix this code run correctly
You should make origlat, origlong global variables, instead of local variable.
http://www.w3schools.com/js/js_scope.asp

google maps javascript v3 api not working

I've tried all possible solutions but the map just isn't showing. My webview just shows blank.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="theme.css">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript">
var map; " +
function initialize() {
var latitude = 0;
var longitude = 0;
if (window.android){
latitude = window.android.getLatitude();
longitude = window.android.getLongitude();
}
var myOptions = {
zoom: 20,
center: myLatLng
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
}
function centerAt(latitude, longitude){
myLatlng = new google.maps.LatLng(latitude,longitude);
map.panTo(myLatLng);
}
</script>
<title>Insert title here</title>
</head>
<body>
<div id="map_canvas" style="height: 100px; width=100px;">This is the map canvas</div>
<script type="text/javascript">initialize();</script>
</body>
</html>
I've narrowed down to this line: map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
When this line is executed, it fails.
Any help is appreciated.
Thanks.
Regards,
Dexter
I can't see myLatLng definition other than in centerAt() function. You need to pass Google Maps LatLng object to the center attribute of myOptions:
var myLatlng = new google.maps.LatLng(latitude, longitude);
var myOptions = {
zoom: 20,
center: myLatLng
}
...
And there is also a strange thing which I can't understand:
var map; " +
^ ^
my bad, submitted the wrong code. Anyway, the major issue here is the connection. That took me a long time to realize it since i was just focusing on the codes.
Thanks.

Centering a google map with javascript from pin

I have my page so that it allows the user to see their latitude and longitude. I've embedded a google map so that the user can click physically see where they're at. This is a project for my computer science class, so I don't want you to physically write the code for me. I just want suggestions on how to solve this. Here's what I have right now.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- This page will allow the suer to track their location through means of the HTML5 Geolocation feature -->
<title>Assignment 4:Track My Location</title>
<meta name="author" content="Alan Sylvestre" />
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function myLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationReveal);
} else {
alert("Please use a different browser that supports geolocation.");
}
}
window.onload = myLocation;
function locationReveal(position) {
showMap(position.coords);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
var map;
function showMap(coords) {
var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
var mapOptions = {
zoom : 18,
center : googleLatAndLong,
mapTypeId : google.maps.MapTypeId.SATELLITE
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
addMarker(googleLatAndLong);
}
google.maps.Map(mapDiv, mapOptions);
var marker;
function addMarker(latlong) {
var markerOptions = {
position : latlong,
map : map
};
marker = new google.maps.Marker(markerOptions);
}
var center;
function calculateCenter() {
center = map.getCenter();
}
</script>
</head>
<body style="background-color:yellow;" text="blue;">
<div align="center">
<h1>Reveal My Location</h1>
<p>
You know what's pretty cool? Tracking your location using a simple internet connection. By clicking this button, you're browser will track a global database and reveal your location in terms of latitude and longitude. Enjoy!
</p>
<div id="location"></div>
<br>
<div id="map" style="width:400px; height:400px;"></div>
<br>
<input type="button" id="centerOfMap" value="Center" onclick="calculateCenter()">
<footer>
<p>
© Copyright by Alan Sylvestre
</p>
</footer>
</div>
</body>
First you need to make sure that the DOM is loaded before you run your JavaScript.
That is why 'mapDiv' is 'undefined'.
Either wrap your script in a window.onload anonymous function or push it to just before the closing body tag.

Categories