Does someone know how to get weather information in Titanium? I read that the Google Weather API is no longer available. I have tried this link but I can't figure out how to put this to work.
Does someone have a working code? I would like to get the weather on my position given by longitude and latitude.
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
return;
} else {
var lon = e.coords.longitude;
var lat = e.coords.latitude;
if (Ti.Network.networkType == Ti.Network.NETWORK_NONE) {
return;
} else {
var client = Ti.Network.createHTTPClient({
onload : function(e) {
var weather = JSON.parse(this.responseText);
getweatherIcon(weather.weather[0].icon);
setweatherText(weather.weather[0].id, weather.main.temp);
},
onerror : function(e) {
},
timeout : 150000
});
client.open("GET", "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=CreatedAppID");
client.send();
}
}
});
The "CreatedAppID" is the ID that I have created after creating an account on the provided link that is above.
I have an app that calls an api and returns a list of locations.
Once the data is returned, I convert the JSON to map points for annotations.
These get added to the ma with no problem.
The problem I am running into is setting the bounds of the map. I can't seem to figure it out.
The code I currently have is.
_handleResponse(response) {
var locations = [];
// Loop through repsone and add items to an arra for annotations
for (var i = 0; i < response.length; i++) {
// Get the location
var location = response[i];
// Parse the co ords
var lat = parseFloat(location.Latitude);
var lng = parseFloat(location.Longitude);
// Add the location to array
locations.push({
latitude: lat,
longitude: lng,
title: location.Name
});
}
// This calls the map set state
this.setState({
annotations: locations
});
}
and here is my view code
<View style={styles.container}>
<MapView
style={styles.map}
onRegionChangeComplete={this._onRegionChangeComplete}
annotations={this.state.annotations}
/>
</View>
You'll want
<MapView
...
region={region}
/>
where
var region = {
latitude,
longitude,
latitudeDelta,
longitudeDelta,
};
latitude and longitude are the center of the map and the deltas are the distance (in degrees) between the minimum and maximum lat/long shown. For instance, given a certain radius in miles around a point and an aspect ratio of the map view, you could calculate region as follows:
var radiusInRad = radiusInKM / earthRadiusInKM;
var longitudeDelta = rad2deg(radiusInRad / Math.cos(deg2rad(latitude)));
var latitudeDelta = aspectRatio * rad2deg(radiusInRad);
The definitions of rad2deg, deg2rad, and earthRadiusInKM are left as an exercise to the reader.
Here is my complete code based on #Philipp's answer:
import React, { Component } from 'react';
import { MapView } from 'react-native';
const earthRadiusInKM = 6371;
// you can customize these two values based on your needs
const radiusInKM = 1;
const aspectRatio = 1;
class Map extends Component {
constructor(props) {
super(props);
// this will be the map's initial region
this.state = {
region : {
latitude: 0,
longitude: 0
}
};
}
// you need to invoke this method to update your map's region.
showRegion(locationCoords) {
if (locationCoords && locationCoords.latitude && locationCoords.longitude) {
var radiusInRad = radiusInKM / earthRadiusInKM;
var longitudeDelta = this.rad2deg(radiusInRad / Math.cos(this.deg2rad(locationCoords.latitude)));
var latitudeDelta = aspectRatio * this.rad2deg(radiusInRad);
this.setState({
region: { latitude: locationCoords.latitude, longitude: locationCoords.longitude, latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta }
});
}
}
render () {
return (
<MapView
style={{flex: 1}}
region={this.state.region}/>
)
}
deg2rad (angle) {
return angle * 0.017453292519943295 // (angle / 180) * Math.PI;
}
rad2deg (angle) {
return angle * 57.29577951308232 // angle / Math.PI * 180
}
}
We are trying to find suggestions, or implementation options on how to hide a marker once a new point on the map has been clicked.
In our application, once the user clicks on a particular pin on the map, we display a new pin (in a different lat/long location) that is associated with the click event. I.e. a point should be in oklahoma, but the map is displaying texas, so once the marker texas is clicked, a new marker in oklahoma is shown. Our issue is that whenever a user selects a new point, we are not able to "hide" the marker for the previous selection, which then clutters our screen.
Any suggestions on how we could handle this issue?
Code is below:
require(["esri/map", "esri/geometry/Point", "esri/symbols/SimpleMarkerSymbol", "esri/graphic", "dojo/_base/array", "dojo/dom-style", "dojox/widget/ColorPicker", "esri/InfoTemplate", "esri/Color", "dojo/dom", "dojo/domReady!", "esri/geometry/Polyline", "esri/geometry/geodesicUtils", "esri/units","esri/symbols/SimpleLineSymbol"],
function( Map, Point,SimpleMarkerSymbol, Graphic, arrayUtils, domStyle, ColorPicker, InfoTemplate, Color, dom, Polyline, geodesicUtils, Units,SimpleLineSymbol) {
map = new Map("mapDiv", {
center : [-98.35, 35.50],
zoom : 5,
basemap : "topo"
//basemap types: "streets", "satellite", "hybrid", "topo", "gray", "oceans", "osm", "national-geographic"
} );
map.on("load", pinMap);
var arr = [];
var initColor, iconPath;
function pinMap( ) {
map.graphics.clear();
iconPath = "M16,3.5c-4.142,0-7.5,3.358-7.5,7.5c0,4.143,7.5,18.121,7.5,18.121S23.5,15.143,23.5,11C23.5,6.858,20.143,3.5,16,3.5z M16,14.584c-1.979,0-3.584-1.604-3.584-3.584S14.021,7.416,16,7.416S19.584,9.021,19.584,11S17.979,14.584,16,14.584z";
var infoContent = "<b>Id</b>: ${Id} ";
var infoTemplate = new InfoTemplate(" Details",infoContent);
$.post( '{{ path( 'points' ) }}', {}, function( r ) {
arrayUtils.forEach( r.points, function( point ) {
if (point.test==1) {
initColor = "#CF3A3A";
}
else {
initColor = "#FF9900";
}
arr.push(point.id,point.pinLon1,point.pinLat1,point.pinLon2,point.pinLat2);
var attributes = {"Site URL":point.url,"Activity Id":point.id,"Updated By":point.updated,"Customer":point.customer};
var graphic = new Graphic(new Point(point.pinLon1,point.pinLat1),createSymbol(iconPath,initColor),attributes,infoTemplate);
map.graphics.add( graphic );
map.graphics.on("click",function(evt){
var Content = evt.graphic.getContent();
var storeId = getStoreId(Content);
sitePins(storeId);
});
} );
}, 'json' );
}
function getStoreId( content ){
var init = content.split(":");
var fin= init[2].split("<");
return fin[0].trim();
}
function sitePins( siteId ) {
iconPathSite = "M15.834,29.084 15.834,16.166 2.917,16.166 29.083,2.917z";
initColorSite = "#005CE6";
var infoContent = "<b>Distance</b>: ${Distance} Miles";
var infoTemplate = new InfoTemplate(" Distance to Location",infoContent);
var indexValue=0;
for (var index = 0; index < arr.length; index++){
if (arr[index]==storeId){
indexValue =index;
}
}
pinLon1 = arr[indexValue+1];
pinLat1 = arr[indexValue+2];
pinLon2 = arr[indexValue+3];
pinLat2 = arr[indexValue+4];
var line = {"paths":[[[pinLon1, pinLat1], [pinLon2, pinLat2]]]};
line = new esri.geometry.Polyline(line);
var lengths = Number(esri.geometry.geodesicLengths([line], esri.Units.MILES)).toFixed(2);
var attributes = {"Distance":lengths};
var graphicSite = new Graphic(new Point (pinLon1,pinLat1), createSymbol(iconPathSite, initColorSite),attributes,infoTemplate);
var pathLine = new esri.Graphic(line, new esri.symbol.SimpleLineSymbol());
map.graphics.add( pathLine );
map.graphics.add( graphicSite );
}
function createSymbol( path, color ) {
var markerSymbol = new esri.symbol.SimpleMarkerSymbol( );
markerSymbol.setPath(path);
markerSymbol.setSize(18);
markerSymbol.setColor(new dojo.Color(color));
markerSymbol.setOutline(null);
return markerSymbol;
}
} );
</script>
As far as I get the code, it shows the distance between the marker and the point then clicked.You are creating point and polyline on each click event on map. Following can help:
1) Please provide id say 'abc' to polyline, graphic site.
2) Then on every click event remove the graphic and polyline with id 'abc'.
dojo.forEach(this.map.graphics.graphics, function(g) {
if( g && g.id === "abc" ) {
//remove graphic with specific id
this.map.graphics.remove(g);
}
}, this);
3) Then you can create the new polyline and point as you are already doing it.
I 'm using the code 'http://developer.appcelerator.com/question/132508/how-to-add-annotation-on-mapview-click-event' to calculate the lat and long.
But I getting some trouble in add a annotation.
The calculate result of long and lat is not correct so the point putted at wrong position
It's my problem or the method is not work now?
mapView.addEventListener('longpress', function(e) {
var coordinate = calculateLatLngfromPixels(mapView, e.x, e.y);
var longitude = coordinate.lon;
var latitude = coordinate.lat;
//var longitude = e.coords.longitude;
//var latitude = e.coords.latitude;
var annotation = Titanium.Map.createAnnotation({
latitude : latitude,
longitude : longitude,
title : "New Place",
//subtitle : 'My Place',
animate : true,
id : 1,
pincolor : Titanium.Map.ANNOTATION_RED
});
mapView.addAnnotation(annotation);
var region = {
latitude : latitude,
longitude : longitude,
animate : true
//latitudeDelta : 0.002,
//longitudeDelta : 0.002
};
mapView.setLocation(region);
alert('latitude'+latitude+' longitude'+longitude);
});
Thank you.
createMap:
var mapView = Ti.Map.createView({
mapType: mapModule.NORMAL_TYPE,
//latitudeDelta: 0.002, longitudeDelta:0.002 : Zoom Level
region : {
latitude : curr_latitude,
longitude : curr_longitude,
latitudeDelta : 0.002,
longitudeDelta : 0.002
},
top : 5,
bottom : 5,
left : 5,
right : 5,
animate : true,
regionFit : true,
userLocation : true
});
You need difference between iOS and Android at listener and callback. I have created Mobile Project (Titanium SDK 3.3.0GA, Map 2.0.2 iOS | 2.1.4 Android)
ApplicationWindow.js
//Application Window Component Constructor
function ApplicationWindow() {
//create component instance
var self = Ti.UI.createWindow({
backgroundColor:'#ffffff'
});
var calculateLatLngfromPixels = function(mapview, xPixels, yPixels) {
var region = mapview.region;
var heightDegPerPixel = -region.latitudeDelta / mapview.rect.height;
var widthDegPerPixel = region.longitudeDelta / mapview.rect.width;
return {
lat : (yPixels - mapview.rect.height / 2) * heightDegPerPixel + region.latitude,
lon : (xPixels - mapview.rect.width / 2) * widthDegPerPixel + region.longitude
};
};
var mapModule = require('ti.map');
var mapView = mapModule.createView({
top: 0,
left: 0,
mapType: mapModule.NORMAL_TYPE
});
var addNewAnnotation = function addNewAnnotation(lat, lng){
Ti.API.info("New Annotation at: {"+lat+", "+lng+"}");
var annotation = mapModule.createAnnotation({
latitude : lat,
longitude : lng,
title : "New Place",
animate : true,
id : 1,
pincolor : mapModule.ANNOTATION_RED
});
mapView.addAnnotation(annotation);
};
if(Ti.Platform.osname === 'android'){
mapView.addEventListener('longclick', function(e) {
addNewAnnotation(e.latitude, e.longitude);
});
}
else {
mapView.addEventListener('longpress', function(e) {
var coordinates = calculateLatLngfromPixels(mapView, e.x, e.y);
addNewAnnotation(coordinates.lat, coordinates.lon);
});
}
self.add(mapView);
return self;
}
//make constructor function the public component interface
module.exports = ApplicationWindow;
I have compared two annotations on New York (Central Park and Apple Store) and the two coordinates are equals. This code works on iOS 7.1 and Android 4.4. More zoom, more accuracy.
I am having some problems using the gem gmaps4rails. I am using a mix of javascript and gmaps4rails. Here is a sample of my code:
function handle_locations(position) {
alert("Length = " + Gmaps.map.markers.length);
var yourStartLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var marker = new google.maps.Marker({position: yourStartLatLng});
alert("Ola 2");
if(document.getElementById("map") != null)
alert("diff");
Gmaps.map.markers[0] = marker;
alert("Ola 333");
//var map = $document.filter('#map');
//var map = document.getElementById("map");
//Gmaps.map.add_marker(marker);
}
navigator.geolocation.getCurrentPosition(handle_locations);
The handle_locations function works fine and i can get my location. The problem is to add a marker to the map created using gmaps. how can i add my geolocaton marker to the map in this function?
I had similar problem and this worked for me.
lat = position.coords.latitude;
lng = position.coords.longitude;
Gmaps.map.callback = function() {
Gmaps.map.createMarker({
Lat: lat,
Lng: lng,
rich_marker: null,
marker_picture: ""
});
}
Make sure you use position.coords.latitude/longitude only after the navigator.geolocation.getCurrentPosition(function(position) {
request has succeeded (propably you are doing so), because getting the location from user is asyncronous and will take some time.
You can check that you have the right lat and lng with
alert(lat+" "+lng);