open layer 4 find address from onclick coordinates - openlayers-3

i am new to open layers, i need to know that is it good to use openstreetmap link to get country Name from given lat,long(for commercial purpose) although it is free but is it a good practice. This is the link which provides country Name in JSON format when latitude and longitude passed as parameters. :-
https://nominatim.openstreetmap.org/reverse?format=json&lat=22.3444&lon=74.123123&limit=1

The div element where is your map: (must be placed into the of the html file)
<div id="id_map" style="height: 100%;"></div>
OpenLayers Javascript code of the map:
// URL of the TILE SERVER
const url_carto_cdn = 'http://{1-4}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png';
// Our map
const map = new ol.Map({
target: document.getElementById('id_map'),
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({url: url_carto_cdn})
})
],
view: new ol.View({
// Centered in Europe
center: ol.proj.fromLonLat([0, 30]),
zoom: 4
})
});
The Javascript function who sends the request Nominatim to get the address when you click on the map:
function httpGet(url, callback_function) {
const getRequest = new XMLHttpRequest();
getRequest.open("get", url, true);
getRequest.addEventListener("readystatechange", function () {
// IF RESPONSE is GOOD
if (getRequest.readyState === 4 && getRequest.status === 200) {
// Callback for making stuff with the Nominatim response address
callback_function(getRequest.responseText);
}
});
// Send the request
getRequest.send();
}
The Javascript of the Mouse-Click event:
// EVENT ON MOUSE CLICK
map.on('click', function (evt) {
// Coords of click is evt.coordinate
console.log("evt.coordinate: " + evt.coordinate);
// You must transform the coordinates because evt.coordinate
// is by default Web Mercator (EPSG:3857)
// and not "usual coords" (EPSG:4326)
const coords_click = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
console.log("Mouse Click coordinates: " + coords_click);
// MOUSE CLICK: Longitude
const lon = coords_click[0];
// MOUSE CLICK: Latitude
const lat = coords_click[1];
// DATA to put in NOMINATIM URL to find address of mouse click location
const data_for_url = {lon: lon, lat: lat, format: "json", limit: 1};
// ENCODED DATA for URL
const encoded_data = Object.keys(data_for_url).map(function (k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(data_for_url[k])
}).join('&');
// FULL URL for searching address of mouse click
const url_nominatim = 'https://nominatim.openstreetmap.org/reverse?' + encoded_data;
console.log("URL Request NOMINATIM-Reverse: " + url_nominatim);
// GET URL REQUEST for ADDRESS
httpGet(url_nominatim, function (response_text) {
// JSON Data of the response to the request Nominatim
const data_json = JSON.parse(response_text);
// Longitude and latitude
const res_lon = data_json.lon;
const res_lat = data_json.lat;
// All the informations of the address are here
const res_address = data_json.address;
// Details depends on the location, country and places
// For example: in the desert, road or pedestrian is
// probably set to undefined because of none...
const address_display_name = data_json.display_name;
const address_country = res_address.country;
const address_country_code = res_address.country_code;
const address_postcode = res_address.postcode;
const address_state = res_address.state;
const address_town = res_address.town;
const address_city = res_address.city;
const address_city_district = res_address.city_district;
const address_suburb = res_address.suburb;
const address_neighbourhood = res_address.neighbourhood;
const address_footway = res_address.footway;
const address_house_number = res_address.house_number;
const address_pedestrian = res_address.pedestrian;
const address_road = res_address.road;
console.log("Longitude : " + res_lon);
console.log("Longitude : " + res_lat);
console.log("Name : " + address_display_name);
console.log("Country : " + address_country);
console.log("Count. Code : " + address_country_code);
console.log("Postcode : " + address_postcode);
console.log("State : " + address_state);
console.log("Town : " + address_town);
console.log("City : " + address_city);
console.log("City District: " + address_city_district);
console.log("Suburb : " + address_suburb);
console.log("Neighbourhood: " + address_neighbourhood);
console.log("Road : " + address_road);
console.log("Footway : " + address_footway);
console.log("Pedestrian : " + address_pedestrian);
console.log("House Number : " + address_house_number);
});
});
All the informations relative to the address near to the mouse click appears in the console log (F12 in Firefox).

Related

ERROR TypeError: null is not an object (evaluating 'this._icon.imageSource.ios')

I'm trying to get custom marker icon on map. I have used nativescript-google-maps-sdk v^2.9.1 and I'm getting following error.
CONSOLE LOG file:///node_modules/#nativescript/core/image-source/image-source.js:306:0: fromResource() is deprecated. Use ImageSource.fromResourceSync() instead.
CONSOLE ERROR file:///node_modules/#angular/core/fesm5/core.js:4002:0: ERROR TypeError: null is not an object (evaluating 'this._icon.imageSource.ios')
the code added to get marker on map is
addMarker(mark, index): void {
const marker = new Marker();
marker.position = Position.positionFromLatLng(mark.latitude, mark.longitude);
// marker.icon = this.ocean_pin; // default pin
const is24 = (isIOS ? '_24' : '');
marker.icon = 'https://www.iconsdb.com/icons/preview/red/map-marker-2-xxl.png';//'https://mob-app-assets.s3.eu-west-2.amazonaws.com/pin_ocean' + is24 + '.png'; // default pin
this.mapView.addMarker(marker);
this.mMarkers.push(marker); // to update marker pin when carousel swiped
}
previously I was using icon from assets, and it was working like a charm. Find the code below that was working for icons from assets.
import * as imageSource from 'tns-core-modules/image-source';
import { Image } from 'tns-core-modules/ui/image/image';
constructor() {
super();
this.buttonHeight = isAndroid ? 45 : 35;
const is24 = (isIOS ? '_24' : '');
this.ocean_pin = new Image();
this.ocean_pin.src = '~assets/icons/pin_ocean' + is24 + '.png';
this.ocean_pin.imageSource = imageSource.fromFile('~assets/icons/pin_ocean' + is24 + '.png');
this.pink_pin = new Image();
this.pink_pin.src = '~assets/icons/pin_pink' + is24 + '.png';
this.pink_pin.imageSource = imageSource.fromFile('~assets/icons/pin_pink' + is24 + '.png');
}
I don't know what has went wrong. But now it's not working for icons from URL.

href for link in google maps

I use geocoder in my app and to show the markers on the map, using json.
it look like this:
...
$.get("get_organizations.json", function( data ) {
$.each( data, function( index, organization ) {
var organizationLatLng = new google.maps.LatLng( organization.latitude, organization.longitude );
var infowindow = new google.maps.InfoWindow({content: contentString});
var contentString = organization.title;
var marker = new google.maps.Marker({
position: organizationLatLng,
map: map,
title: organization.title
});
and all works fine, but I want to link in infowindow and need solution in this question!
if I change value of contentString, I don't know what should be in href of link
var contentString = '' + organization.title + '';
link should redirect to the selected organization in infowindow!
thanks in advance!
Assume you have a REST route and the relative path to an organization looks like /organizations/1234 where 1234 it is id of organization:
var orgId = organization.id;
var orgTitle = organization.title;
var contentString = '' + orgTitle + '';

Trying to eliminate closure error in google map eventListener

I have a google map with a load of markers on it, each corresponding to a different post in the html. Each marker id is the same as each post id. Inside the map initialize = function() {... I have the following code (I'm using gon to pass info from rails to javascript):
for (m = 0; m < gon.markers.length; m++) {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(gon.markers[m].lat, gon.markers[m].lng),
icon: image,
infowindow: gon.markers[m].infowindow,
id: gon.markers[m].id
});
google.maps.event.addListener(marker, 'mouseover', function() {
var image = $("#map-canvas").data('marker2');
this.setIcon(image);
// console.log("marker.id: " + marker.id);
// console.log("this.id" + this.id);
$('#' + marker.id).css('background', 'red');
});
google.maps.event.addListener(marker, 'mouseout', function() {
var image = $("#map-canvas").data('marker1');
this.setIcon(image);
$('#' + marker.id).css('background', 'white');
});
markers[markers.length] = marker;
}
Uncommenting the console.log lines demonstrates that it is the classic closure problem (marker.id always has the same value no matter which marker is hovered on).
My question is, how do I code it properly so it does as intended? I just can't get the code right now matter what I try. I've tried stuff like this but is just doesn't work:
marker.on('mouseover', noticeHover(marker.id));
function noticeHover(id) {
var image = $("#map-canvas").data('marker2');
this.setIcon(image);
$('#' + id).css('background', 'gainsboro');
}
Wrap the entire code that handles the marker-creation into a function and pass the items inside the loop as argument to this function:
for (m = 0; m < gon.markers.length; m++) {
//anonymous,self-executing function
(function(props){
var goo = google.maps,
marker = new goo.Marker({
map: map,
position: new goo.LatLng(props.lat,
props.lng),
icon: image,
infowindow: props.infowindow,
id: props.id
});
goo.event.addListener(marker, 'mouseover', function() {
var image = $("#map-canvas").data('marker2');
this.setIcon(image);
$('#' + marker.id).css('background', 'red');
});
goo.event.addListener(marker, 'mouseout', function() {
var image = $("#map-canvas").data('marker1');
this.setIcon(image);
$('#' + marker.id).css('background', 'white');
});
markers.push(marker);
}(
gon.markers[m]//pass current loop-item as argument
));
}

How to upload powerpoint file to server phonegap?

Hello I Want to upload a powerpoint file using phonegap file transfer protocol to my local java server thru ios simulator, the location of the file on the phone is passed to the handleOpenURL function when the user selects to open a powerpoint with my app. The problem is that nothing is happening although im sure this method is executing??!! can anyone help please?
function handleOpenURL(url)
{
setTimeout(function() {
alert(url);
jQuery.get( "http://192.168.1.100:8080/PpServer/getnumberofslides" , function( data ) {
numberofslides=data;
alert( "Load was performed." + data );
});
fileURL = url;
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// processapplication();
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var uri = encodeURI("http://192.168.1.100:8080/NewServerlet");
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType="multipart/form-data";
options.httpMethod="Post"
// options.params = {"file"};
var headers={'headerParam':'file'};
// options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
} else {
loadingStatus.increment();
}
};
ft.upload(fileURL, uri, win, fail, options);
}, 0);
//
}

How can I use a RESTful JSONResult from my controller to populate Bing Maps Geocoding?

I know there are a few topics on this, but I seem to be fumbling my way through with no results. I'm trying to use a controller to return JSON results to my Bing Maps functions.
Here's what I have for my controller (yes it is properly returning JSON data.
Function Regions() As JsonResult
Dim rj As New List(Of RtnJson)()
rj.Add(New RtnJson("135 Bow Meadows Drive, Cochrane, Alberta", "desc", "title"))
rj.Add(New RtnJson("12 Bowridge Dr NW, Calgary, Alberta, Canada", "desc2", "title2"))
Return Json(rj, JsonRequestBehavior.AllowGet)
End Function
Then in my script I have this, but it's not working.
<script type="text/javascript">
var map = null;
var centerLat = 51.045 ;
var centerLon = -114.05722;
var path = "<%: Url.Action("GetRegions", "Regions")%>";
function LoadMap() {
map = new VEMap('bingMap');
map.LoadMap(new VELatLong(centerLat, centerLon), 10);
$.getJSON(path, function(json){
$.each(json, function(){
alert(this.address); // the alert message is "undefined"
StartGeocoding(this.address, this.title, this.description);
});
});
}
function StartGeocoding(address, title, desc) {
map.Find(null, // what
address, // where
null, // VEFindType (always VEFindType.Businesses)
null, // VEShapeLayer (base by default)
null, // start index for results (0 by default)
null, // max number of results (default is 10)
null, // show results? (default is true)
null, // create pushpin for what results? (ignored since what is null)
true, // use default disambiguation? (default is true)
false, // set best map view? (default is true)
GeocodeCallback); // call back function
}
function GeocodeCallback(shapeLayer, findResults, places, moreResults, errorMsg) {
var bestPlace = places[0];
// Add pushpin to the *best* place
var location = bestPlace.LatLong;
var newShape = new VEShape(VEShapeType.Pushpin, location);
var desc = "Latitude: " + location.Latitude + "<br>Longitude:" + location.Longitude;
newShape.SetDescription(desc);
newShape.SetTitle(bestPlace.Name);
map.AddShape(newShape);
}
$(document).ready(function () {
LoadMap();
});
</script>
Well damn.
Turns out that I was using this.address when I should have been using this.Address. Can't believe I missed that.

Resources