Commit 5e943ba2 authored by Deployer's avatar Deployer

Importing initial version of CedarMaps AndroidSDK

parents
.gradle
.idea
*.iml
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
version = "0.7.0"
def siteUrl = 'http://cedarmaps.com'
def gitUrl = 'http://cedarmaps.com/git'
group = "com.cedarmaps"
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
minSdkVersion 9
targetSdkVersion 21
versionCode 1
versionName "0.7.0"
}
buildTypes {
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('com.mapbox.mapboxsdk:mapbox-android-sdk:0.7.0@aar') {
transitive = true
}
}
install {
repositories.mavenInstaller {
// This generates POM.xml with proper parameters
pom {
project {
packaging 'aar'
// Add your description here
name 'CedarMpas SDK for Android'
url siteUrl
// Set your license
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id 'cedarstudios'
name 'CedarStudios'
email 'info@cedarstudios.com'
}
}
scm {
connection gitUrl
developerConnection gitUrl
url siteUrl
}
}
}
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar
archives sourcesJar
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in I:/Reza/Programming/Android/android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
package com.cedarstudios.cedarmapssdk;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
\ No newline at end of file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cedarstudios.cedarmapssdk">
<application android:allowBackup="true" android:label="@string/app_name">
</application>
</manifest>
package com.cedarstudios.cedarmapssdk;
import com.cedarstudios.cedarmapssdk.auth.OAuth2Support;
import org.json.JSONObject;
public interface CedarMaps extends OAuth2Support, CedarMapsBase {
JSONObject geocode(String searchTerm) throws CedarMapsException;
JSONObject geocode(String searchTerm, String city) throws CedarMapsException;
JSONObject geocode(String searchTerm, String city, double lat, double lng)
throws CedarMapsException;
JSONObject geocode(String searchTerm, String city, double lat, double lng, long distance)
throws CedarMapsException;
JSONObject geocode(String searchTerm, String city, double lat, double lng, long distance,
int limit) throws CedarMapsException;
JSONObject geocode(double lat, double lng) throws CedarMapsException;
}
package com.cedarstudios.cedarmapssdk;
import com.cedarstudios.cedarmapssdk.auth.Authorization;
import com.cedarstudios.cedarmapssdk.config.Configuration;
public interface CedarMapsBase {
/**
* Returns the authorization scheme for this instance.<br>
* The returned type will be either of OAuthAuthorization or NullAuthorization
*
* @return the authorization scheme for this instance
*/
Authorization getAuthorization();
/**
* Returns the configuration associated with this instance
*
* @return configuration associated with this instance
* @since CedarMaps 0.5
*/
Configuration getConfiguration();
}
package com.cedarstudios.cedarmapssdk;
import com.cedarstudios.cedarmapssdk.auth.Authorization;
import com.cedarstudios.cedarmapssdk.auth.NullAuthorization;
import com.cedarstudios.cedarmapssdk.auth.OAuth2Authorization;
import com.cedarstudios.cedarmapssdk.auth.OAuth2Support;
import com.cedarstudios.cedarmapssdk.auth.OAuth2Token;
import com.cedarstudios.cedarmapssdk.config.Configuration;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
abstract class CedarMapsBaseImpl implements CedarMapsBase, Serializable, OAuth2Support {
Configuration conf;
Authorization auth;
CedarMapsBaseImpl(Configuration conf, Authorization auth) {
this.conf = conf;
this.auth = auth;
init();
}
private void init() {
if (null == auth) {
// try to populate OAuthAuthorization if available in the configuration
String clientId = conf.getOAuthClientId();
String clientSecret = conf.getOAuthClientSecret();
// try to find oauth tokens in the configuration
if (clientId != null && clientSecret != null) {
OAuth2Authorization oauth2 = new OAuth2Authorization(conf);
String tokenType = conf.getOAuth2TokenType();
String accessToken = conf.getOAuth2AccessToken();
if (tokenType != null && accessToken != null) {
oauth2.setOAuth2Token(new OAuth2Token(tokenType, accessToken));
}
this.auth = oauth2;
} else {
this.auth = NullAuthorization.getInstance();
}
}
}
@Override
public final Authorization getAuthorization() {
return auth;
}
@Override
public Configuration getConfiguration() {
return this.conf;
}
final void ensureAuthorizationEnabled() {
if (!auth.isEnabled()) {
throw new IllegalStateException("Authentication credentials are missing. ");
}
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// http://docs.oracle.com/javase/6/docs/platform/serialization/spec/output.html#861
out.putFields();
out.writeFields();
out.writeObject(conf);
out.writeObject(auth);
}
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
// http://docs.oracle.com/javase/6/docs/platform/serialization/spec/input.html#2971
stream.readFields();
conf = (Configuration) stream.readObject();
auth = (Authorization) stream.readObject();
}
// methods declared in OAuthSupport interface
@Override
public synchronized OAuth2Token getOAuth2Token() throws CedarMapsException {
return getOAuth2().getOAuth2Token();
}
@Override
public void setOAuth2Token(OAuth2Token oauth2Token) {
getOAuth2().setOAuth2Token(oauth2Token);
}
@Override
public synchronized void invalidateOAuth2Token() throws CedarMapsException {
getOAuth2().invalidateOAuth2Token();
}
private OAuth2Support getOAuth2() {
if (!(auth instanceof OAuth2Support)) {
throw new IllegalStateException(
"OAuth client id/secret combination not supplied");
}
return (OAuth2Support) auth;
}
}
package com.cedarstudios.cedarmapssdk;
public class CedarMapsConstants {
public final static String CEDARMAPS_BASE_URL_V1 = "http://api.cedarmaps.com/v1/";
}
package com.cedarstudios.cedarmapssdk;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class CedarMapsException extends Exception {
private Response response;
private int statusCode = -1;
private String errorMessage = null;
public CedarMapsException(String message, Throwable cause) {
super(message, cause);
}
public CedarMapsException(String message) {
this(message, (Throwable) null);
}
public CedarMapsException(Exception cause) {
this(cause.getMessage(), cause);
if (cause instanceof CedarMapsException) {
((CedarMapsException) cause).setNested();
}
}
public CedarMapsException(String message, Response res) {
this(message);
response = res;
this.statusCode = res.code();
}
public CedarMapsException(String message, Exception cause, int statusCode) {
this(message, cause);
this.statusCode = statusCode;
}
@Override
public String getMessage() {
StringBuilder value = new StringBuilder();
if (errorMessage != null) {
value.append("message - ").append(errorMessage)
.append("\n");
} else {
value.append(super.getMessage());
}
if (statusCode != -1) {
return getCause(statusCode) + "\n" + value.toString();
} else {
return value.toString();
}
}
public int getStatusCode() {
return this.statusCode;
}
/**
* Tests if the exception is caused by network issue
*
* @return if the exception is caused by network issue
* @since CedarMaps 0.5
*/
public boolean isCausedByNetworkIssue() {
return getCause() instanceof IOException;
}
private boolean nested = false;
void setNested() {
nested = true;
}
/**
* Returns error message from the API if available.
*
* @return error message from the API
* @since CedarMaps 0.5
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* Tests if error message from the API is available
*
* @return true if error message from the API is available
* @since CedarMaps 0.5
*/
public boolean isErrorMessageAvailable() {
return errorMessage != null;
}
private static String getCause(int statusCode) {
String cause;
switch (statusCode) {
case 401:
cause
= "Authentication credentials were missing or incorrect. Ensure that you have set valid client id or secret, access token and the system clock is in sync.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
}
package com.cedarstudios.cedarmapssdk;
import com.cedarstudios.cedarmapssdk.auth.Authorization;
import com.cedarstudios.cedarmapssdk.auth.AuthorizationFactory;
import com.cedarstudios.cedarmapssdk.config.Configuration;
public class CedarMapsFactory {
private static CedarMaps singleton;
private final Configuration configuration;
public CedarMaps getInstance() {
return getInstance(AuthorizationFactory.getInstance(configuration));
}
public CedarMaps getInstance(Authorization auth) {
return new CedarMapsImpl(configuration, auth);
}
public CedarMapsFactory(Configuration configuration) {
this.configuration = configuration;
}
}
package com.cedarstudios.cedarmapssdk;
import com.cedarstudios.cedarmapssdk.auth.Authorization;
import com.cedarstudios.cedarmapssdk.auth.NullAuthorization;
import com.cedarstudios.cedarmapssdk.auth.OAuth2Authorization;
import com.cedarstudios.cedarmapssdk.config.Configuration;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
class CedarMapsImpl extends CedarMapsBaseImpl implements CedarMaps {
CedarMapsImpl(Configuration conf, Authorization auth) {
super(conf, auth);
}
@Override
public JSONObject geocode(String searchTerm) throws CedarMapsException {
return geocode(searchTerm, null);
}
@Override
public JSONObject geocode(String searchTerm, String city) throws CedarMapsException {
return geocode(searchTerm, city, Double.NaN, Double.NaN);
}
@Override
public JSONObject geocode(String searchTerm, String city, double lat, double lng)
throws CedarMapsException {
return geocode(searchTerm, city, lat, lng, -1);
}
@Override
public JSONObject geocode(String searchTerm, String city, double lat, double lng,
long distance) throws CedarMapsException {
return geocode(searchTerm, city, lat, lng, distance, 30);
}
@Override
public JSONObject geocode(String searchTerm, String city, double lat, double lng,
long distance, int limit) throws CedarMapsException {
String term;
if (TextUtils.isEmpty(conf.getMapId())) {
throw new CedarMapsException(new NullPointerException(
"mapId is null. please provide a mapId in configuration"));
}
try {
term = URLEncoder.encode(searchTerm, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CedarMapsException(e);
}
String url = String
.format(Locale.ENGLISH, conf.getRestBaseURL() + "geocode/%s/%s.json",
conf.getMapId(), term);
url += String.format(Locale.ENGLISH, "?limit=%s", limit);
if (!TextUtils.isEmpty(city)) {
url += String.format(Locale.ENGLISH, "&city=%s", city);
}
if (!Double.valueOf(lat).isNaN() && !Double.valueOf(lng).isNaN()) {
url += String.format(Locale.ENGLISH, "&location=%1$s,%2$s", lat, lng);
}
if (distance != -1) {
url += String.format(Locale.ENGLISH, "&distance=%s", distance);
}
try {
return new JSONObject(getDataFromAPI(url));
} catch (JSONException e) {
throw new CedarMapsException(e);
}
}
@SuppressWarnings("SpellCheckingInspection")
@Override
public JSONObject geocode(double lat, double lng) throws CedarMapsException {
String url = String.format(Locale.ENGLISH,
conf.getRestBaseURL() + "geocode/%1$s/%2$s,%3$s.json", conf.getMapId(), lat, lng);
if (TextUtils.isEmpty(conf.getMapId())) {
throw new CedarMapsException(new NullPointerException(
"mapId is null. please provide a mapId in configuration"));
}
try {
return new JSONObject(getDataFromAPI(url));
} catch (JSONException e) {
throw new CedarMapsException(e);
}
}
private String getDataFromAPI(String url) throws CedarMapsException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + conf.getOAuth2AccessToken())
.build();
Response response;
String responseString;
try {
response = client.newCall(request).execute();
responseString = response.body().string();
} catch (Exception e) {
throw new CedarMapsException(e);
}
if (response.code() == 400) {
throw new CedarMapsException("Invalid Request. missing parameter.", response);
} else if (response.code() == 401) {
throw new CedarMapsException("OAuth2 Bearer Token failed.", response);
} else if (response.code() == 500) {
throw new CedarMapsException("Internal Error", response);
}
return responseString;
}
@Override
public void setOAuthClient(String clientId, String clientSecret) {
if (null == clientId) {
throw new NullPointerException("client key is null");
}
if (null == clientSecret) {
throw new NullPointerException("client secret is null");
}
if (auth instanceof NullAuthorization) {
OAuth2Authorization oauth2 = new OAuth2Authorization(conf);
oauth2.setOAuthClient(clientId, clientSecret);
auth = oauth2;
} else if (auth instanceof OAuth2Authorization) {
throw new IllegalStateException("client id/secret pair already set.");
}
}
}
package com.cedarstudios.cedarmapssdk.auth;
public interface Authorization {
boolean isEnabled();
}
package com.cedarstudios.cedarmapssdk.auth;
public interface AuthorizationConfiguration {
String getOAuth2TokenType();
String getOAuth2AccessToken();
}
\ No newline at end of file
package com.cedarstudios.cedarmapssdk.auth;
import com.cedarstudios.cedarmapssdk.config.Configuration;
public final class AuthorizationFactory {
/**
* @param conf configuration
* @since CedarMaps 0.5
*/
public static Authorization getInstance(Configuration conf) {
Authorization auth = null;
String clientId = conf.getOAuthClientId();
String clientSecret = conf.getOAuthClientSecret();
if (clientId != null && clientSecret != null) {
OAuth2Authorization oauth2 = new OAuth2Authorization(conf);
String tokenType = conf.getOAuth2TokenType();
String accessToken = conf.getOAuth2AccessToken();
if (tokenType != null && accessToken != null) {
oauth2.setOAuth2Token(new OAuth2Token(tokenType, accessToken));
}
auth = oauth2;
}
if (null == auth) {
auth = NullAuthorization.getInstance();
}
return auth;
}
}
package com.cedarstudios.cedarmapssdk.auth;
import java.io.Serializable;
public class NullAuthorization implements Authorization, Serializable {
private static final NullAuthorization SINGLETON = new NullAuthorization();
private NullAuthorization() {
}
public static NullAuthorization getInstance() {
return SINGLETON;
}
@Override
public boolean isEnabled() {
return false;
}
}
\ No newline at end of file
package com.cedarstudios.cedarmapssdk.auth;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
import com.cedarstudios.cedarmapssdk.config.Configuration;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONObject;
import java.io.Serializable;
public class OAuth2Authorization implements Authorization, Serializable, OAuth2Support {
private final Configuration conf;
private String clientId;
private String clientSecret;
private OAuth2Token token;
public OAuth2Authorization(Configuration conf) {
this.conf = conf;
setOAuthClient(conf.getOAuthClientId(), conf.getOAuthClientSecret());
}
@Override
public void setOAuthClient(String clientId, String clientSecret) {
this.clientId = clientId != null ? clientId : "";
this.clientSecret = clientSecret != null ? clientSecret : "";
}
@Override
public OAuth2Token getOAuth2Token() throws CedarMapsException {
if (token != null) {
throw new IllegalStateException("OAuth 2 Bearer Token is already available.");
}
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodingBuilder()
.add("client_id", clientId)
.add("client_secret", clientSecret)
.build();
Request request = new Request.Builder()
.url(conf.getOAuth2TokenURL())
.post(formBody)
.build();
JSONObject responseObject;
Response response;
try {
response = client.newCall(request).execute();
responseObject = new JSONObject(response.body().string());
} catch (Exception e) {
throw new CedarMapsException(e);
}
if (response.code() != 200) {
throw new CedarMapsException("Obtaining OAuth2 Bearer Token failed.", response);
}
token = new OAuth2Token(responseObject);
return token;
}
@Override
public void setOAuth2Token(OAuth2Token oauth2Token) {
this.token = oauth2Token;
}
@Override
public void invalidateOAuth2Token() throws CedarMapsException {
//TODO
}
@Override
public boolean isEnabled() {
return token != null;
}
}
package com.cedarstudios.cedarmapssdk.auth;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
public interface OAuth2Support {
/**
* Sets the OAuth client id and client secret.
*
* @param clientId OAuth client id
* @param clientSecret OAuth client secret
* @throws IllegalStateException when OAuth client has already been set, or the instance is
* using basic authorization.
*/
void setOAuthClient(String clientId, String clientSecret);
/**
* Obtains an OAuth 2 Bearer token.
*
* @return OAuth 2 Bearer token
* @throws CedarMapsException when service or network is unavailable, or connecting
* non-SSL endpoints.
* @throws IllegalStateException when Bearer token is already available, or OAuth client is
* not available.
*/
OAuth2Token getOAuth2Token() throws CedarMapsException;
/**
* Sets the OAuth 2 Bearer token.
*
* @param oauth2Token OAuth 2 Bearer token
*/
void setOAuth2Token(OAuth2Token oauth2Token);
/**
* Revokes an issued OAuth 2 Bearer Token.
*
* @throws CedarMapsException when service or network is unavailable, or connecting
* non-SSL endpoints.
* @throws IllegalStateException when Bearer token is not available.
*/
void invalidateOAuth2Token() throws CedarMapsException;
}
package com.cedarstudios.cedarmapssdk.auth;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
import org.json.JSONObject;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class OAuth2Token implements Serializable {
private String tokenType;
private String accessToken;
OAuth2Token(JSONObject json) throws CedarMapsException {
tokenType = json.optString("token_type");
try {
accessToken = URLDecoder.decode(json.optString("access_token"), "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
}
public OAuth2Token(String tokenType, String accessToken) {
this.tokenType = tokenType;
this.accessToken = accessToken;
}
public String getTokenType() {
return tokenType;
}
public String getAccessToken() {
return accessToken;
}
String generateAuthorizationHeader() {
String encoded = "";
try {
encoded = URLEncoder.encode(accessToken, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
return "Bearer " + encoded;
}
}
\ No newline at end of file
package com.cedarstudios.cedarmapssdk.config;
import com.cedarstudios.cedarmapssdk.auth.AuthorizationConfiguration;
import java.io.Serializable;
public interface Configuration extends AuthorizationConfiguration, Serializable {
String getOAuth2TokenType();
String getOAuth2AccessToken();
String getRestBaseURL();
String getOAuth2Scope();
String getOAuth2TokenURL();
String getOAuthClientId();
String getOAuthClientSecret();
String getMapId();
}
package com.cedarstudios.cedarmapssdk.config;
import com.cedarstudios.cedarmapssdk.CedarMapsConstants;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
class ConfigurationBase implements Configuration, Serializable {
private String oAuthClientId;
private String oAuthClientSecret;
private String oAuth2TokenType;
private String oAuth2AccessToken;
private String oAuth2Scope;
private String mapId;
private String oAuth2TokenURL = CedarMapsConstants.CEDARMAPS_BASE_URL_V1 + "token";
private String restBaseURL = CedarMapsConstants.CEDARMAPS_BASE_URL_V1;
public void setOAuthClientId(String oAuthClientId) {
this.oAuthClientId = oAuthClientId;
}
public void setClientSecret(String clientSecret) {
this.oAuthClientSecret = clientSecret;
}
public void setMapId(String mapId) {
this.mapId = mapId;
}
@Override
public String getRestBaseURL() {
return restBaseURL;
}
protected final void setRestBaseURL(String restBaseURL) {
this.restBaseURL = restBaseURL;
}
@Override
public String getOAuth2TokenType() {
return oAuth2TokenType;
}
protected final void setOAuth2TokenType(String oAuth2TokenType) {
this.oAuth2TokenType = oAuth2TokenType;
}
@Override
public String getOAuth2AccessToken() {
return oAuth2AccessToken;
}
@Override
public String getOAuth2Scope() {
return oAuth2Scope;
}
protected final void setOAuth2AccessToken(String oAuth2AccessToken) {
this.oAuth2AccessToken = oAuth2AccessToken;
}
protected final void setOAuth2Scope(String oAuth2Scope) {
this.oAuth2Scope = oAuth2Scope;
}
@Override
public String getOAuth2TokenURL() {
return oAuth2TokenURL;
}
@Override
public String getOAuthClientId() {
return oAuthClientId;
}
@Override
public String getOAuthClientSecret() {
return oAuthClientSecret;
}
@Override
public String getMapId() {
return mapId;
}
protected final void setOAuth2TokenURL(String oAuth2TokenURL) {
this.oAuth2TokenURL = oAuth2TokenURL;
}
private static final List<ConfigurationBase> instances = new ArrayList<ConfigurationBase>();
private static void cacheInstance(ConfigurationBase conf) {
if (!instances.contains(conf)) {
instances.add(conf);
}
}
protected void cacheInstance() {
cacheInstance(this);
}
private static ConfigurationBase getInstance(ConfigurationBase configurationBase) {
int index;
if ((index = instances.indexOf(configurationBase)) == -1) {
instances.add(configurationBase);
return configurationBase;
} else {
return instances.get(index);
}
}
// assures equality after deserialization
protected Object readResolve() throws ObjectStreamException {
return getInstance(this);
}
}
package com.cedarstudios.cedarmapssdk.config;
public final class ConfigurationBuilder {
private ConfigurationBase configurationBase = new ConfigurationBase();
public ConfigurationBuilder setClientId(String clientId) {
checkNotBuilt();
configurationBase.setOAuthClientId(clientId);
return this;
}
public ConfigurationBuilder setClientSecret(String clientSecret) {
checkNotBuilt();
configurationBase.setClientSecret(clientSecret);
return this;
}
public ConfigurationBuilder setMapId(String mapId) {
checkNotBuilt();
configurationBase.setMapId(mapId);
return this;
}
public ConfigurationBuilder setOAuth2TokenType(String oAuth2TokenType) {
checkNotBuilt();
configurationBase.setOAuth2TokenType(oAuth2TokenType);
return this;
}
public ConfigurationBuilder setOAuth2AccessToken(String oAuth2AccessToken) {
checkNotBuilt();
configurationBase.setOAuth2AccessToken(oAuth2AccessToken);
return this;
}
public ConfigurationBuilder setOAuth2Scope(String oAuth2Scope) {
checkNotBuilt();
configurationBase.setOAuth2Scope(oAuth2Scope);
return this;
}
public ConfigurationBuilder setOAuth2TokenURL(String oAuth2TokenURL) {
checkNotBuilt();
configurationBase.setOAuth2TokenURL(oAuth2TokenURL);
return this;
}
public ConfigurationBuilder setRestBaseURL(String restBaseURL) {
checkNotBuilt();
configurationBase.setRestBaseURL(restBaseURL);
return this;
}
public Configuration build() {
checkNotBuilt();
configurationBase.cacheInstance();
try {
return configurationBase;
} finally {
configurationBase = null;
}
}
private void checkNotBuilt() {
if (configurationBase == null) {
throw new IllegalStateException(
"Cannot use this builder any longer, build() has already been called");
}
}
}
package com.cedarstudios.cedarmapssdk.tileprovider;
import com.cedarstudios.cedarmapssdk.CedarMapsConstants;
import com.cedarstudios.cedarmapssdk.utils.CedarMapsUtils;
import com.mapbox.mapboxsdk.tileprovider.tilesource.TileJsonTileLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.TileLayer;
import android.text.TextUtils;
import java.util.Locale;
public class CedarMapsTileLayer extends TileJsonTileLayer {
private String mId;
public CedarMapsTileLayer(String mapId) {
super(mapId, mapId, false);
}
@Override
protected void initialize(String pId, String aUrl, boolean enableSSL) {
mId = pId;
super.initialize(pId, aUrl, enableSSL);
}
@Override
public TileLayer setURL(final String aUrl) {
if (!TextUtils.isEmpty(aUrl) && !aUrl.toLowerCase(Locale.US).contains("http://") && !aUrl
.toLowerCase(Locale.US).contains("https://")) {
super.setURL(
CedarMapsConstants.CEDARMAPS_BASE_URL_V1 + "tiles/" + aUrl
+ "/{z}/{x}/{y}.png?access_token="
+ CedarMapsUtils.getAccessToken());
} else {
super.setURL(aUrl);
}
return this;
}
@Override
protected String getBrandedJSONURL() {
String url = String
.format(Locale.ENGLISH, CedarMapsConstants.CEDARMAPS_BASE_URL_V1
+ "tiles/%s.json?access_token=%s&secure=1", mId,
CedarMapsUtils.getAccessToken());
if (!mEnableSSL) {
url = url.replace("https://", "http://");
url = url.replace("&secure=1", "");
}
return url;
}
public String getCacheKey() {
return mId;
}
}
\ No newline at end of file
package com.cedarstudios.cedarmapssdk.utils;
import com.mapbox.mapboxsdk.util.MapboxUtils;
public class CedarMapsUtils extends MapboxUtils {
}
\ No newline at end of file
<resources>
<string name="app_name">CedarMapsSdk</string>
</resources>
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.cedarstudios.cedarmaps.sample"
minSdkVersion 9
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile(project(':CedarMapsSDK'))
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in I:\Reza\Programming\Android\android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
package com.cedarstudios.cedarmaps;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cedarstudios.cedarmaps.sample" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.cedarstudios.cedarmaps.sample;
public class Constants {
public static final String MAPID_CEDARMAPS_STREETS = "cedarmaps.streets";
public static final String CLIENT_ID = "user";
public static final String CLIENT_SECRET = "pass";
}
package com.cedarstudios.cedarmaps.sample;
import com.cedarstudios.cedarmaps.sample.fragment.APIAdvancedGeocodeTestFragment;
import com.cedarstudios.cedarmaps.sample.fragment.APIGeocodeTestFragment;
import com.cedarstudios.cedarmaps.sample.fragment.APIReverseGeocodeTestFragment;
import com.cedarstudios.cedarmaps.sample.fragment.ItemizedIconOverlayTestFragment;
import com.cedarstudios.cedarmaps.sample.fragment.MainTestFragment;
import com.cedarstudios.cedarmaps.sample.fragment.MarkersTestFragment;
import com.cedarstudios.cedarmapssdk.CedarMaps;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
import com.cedarstudios.cedarmapssdk.CedarMapsFactory;
import com.cedarstudios.cedarmapssdk.auth.OAuth2Token;
import com.cedarstudios.cedarmapssdk.config.ConfigurationBuilder;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private ArrayList<String> testFragmentNames;
private int selectedFragmentIndex = 0;
public static final String PREF_NAME = "pref";
public static final String PREF_ID_ACCESS_TOKEN = "access_token";
public static final String PREF_ID_TOKEN_TYPE = "token_type";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
MapView.setDebugMode(true); //make sure to call this before the view is created!
*/
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
testFragmentNames = new ArrayList<>();
testFragmentNames.add(getString(R.string.mainTestMap));
testFragmentNames.add(getString(R.string.markersTestMap));
testFragmentNames.add(getString(R.string.itemizedOverlayTestMap));
testFragmentNames.add(getString(R.string.searchAPI));
testFragmentNames.add(getString(R.string.streetSearchAPIAdvanced));
testFragmentNames.add(getString(R.string.reverseGeocode));
mDrawerList
.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, testFragmentNames));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.mipmap.ic_drawer, R.string.drawerOpen, R.string.drawerClose) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(testFragmentNames.get(selectedFragmentIndex));
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// Set MainTestFragment
selectItem(0);
new CedarMapsAuthenticateTask().execute();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/**
* Swaps fragments in the main content view
*/
private void selectItem(int position) {
selectedFragmentIndex = position;
// Create a new fragment and specify the planet to show based on position
Fragment fragment;
switch (position) {
case 0:
fragment = new MainTestFragment();
break;
case 1:
fragment = new MarkersTestFragment();
break;
case 2:
fragment = new ItemizedIconOverlayTestFragment();
break;
case 3:
fragment = new APIGeocodeTestFragment();
break;
case 4:
fragment = new APIAdvancedGeocodeTestFragment();
break;
case 5:
fragment = new APIReverseGeocodeTestFragment();
break;
default:
fragment = new MainTestFragment();
break;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(testFragmentNames.get(position));
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
getSupportActionBar().setTitle(title);
}
class CedarMapsAuthenticateTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
com.cedarstudios.cedarmapssdk.config.Configuration
configuration = new ConfigurationBuilder()
.setClientId(Constants.CLIENT_ID)
.setClientSecret(Constants.CLIENT_SECRET)
.build();
CedarMapsFactory factory = new CedarMapsFactory(configuration);
CedarMaps cedarMaps = factory.getInstance();
try {
OAuth2Token oAuth2Token = cedarMaps.getOAuth2Token();
SharedPreferences pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(PREF_ID_ACCESS_TOKEN, oAuth2Token.getAccessToken());
editor.putString(PREF_ID_TOKEN_TYPE, oAuth2Token.getTokenType());
editor.commit();
} catch (CedarMapsException e) {
e.printStackTrace();
}
return null;
}
}
}
package com.cedarstudios.cedarmaps.sample.fragment;
import com.cedarstudios.cedarmaps.sample.Constants;
import com.cedarstudios.cedarmaps.sample.MainActivity;
import com.cedarstudios.cedarmaps.sample.R;
import com.cedarstudios.cedarmapssdk.CedarMaps;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
import com.cedarstudios.cedarmapssdk.CedarMapsFactory;
import com.cedarstudios.cedarmapssdk.config.Configuration;
import com.cedarstudios.cedarmapssdk.config.ConfigurationBuilder;
import com.cedarstudios.cedarmapssdk.tileprovider.CedarMapsTileLayer;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.MapView;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class APIAdvancedGeocodeTestFragment extends Fragment implements View.OnClickListener {
private EditText mSearchEditText;
private MapView mapView;
private ArrayList<Marker> mMarkers = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_search, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
String accessToken = pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, "");
MapView mapView = (MapView) view.findViewById(R.id.mapView);
mapView.setAccessToken(accessToken);
CedarMapsTileLayer cedarMapsTileLayer = new CedarMapsTileLayer(Constants.MAPID_CEDARMAPS_STREETS);
mapView.setTileSource(cedarMapsTileLayer);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mapView.setZoom(12);
view.findViewById(R.id.search).setOnClickListener(this);
mSearchEditText = (EditText) view.findViewById(R.id.term);
mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
view.findViewById(R.id.search).performClick();
return true;
}
return false;
}
});
return view;
}
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mSearchEditText.getText().toString())) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
clearMarkers();
new SearchAsyncTask().execute(mSearchEditText.getText().toString().trim());
}
}
private void clearMarkers() {
for (Marker marker : mMarkers) {
mapView.removeMarker(marker);
}
mapView.setZoom(12);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mMarkers.clear();
mapView.clear();
}
class SearchAsyncTask extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog mProgress;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress = new ProgressDialog(getActivity());
mProgress.setMessage(getString(R.string.searching));
mProgress.show();
}
@Override
protected JSONObject doInBackground(String... params) {
JSONObject searchResult = null;
try {
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
Configuration configuration = new ConfigurationBuilder()
.setOAuth2AccessToken(pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, ""))
.setOAuth2TokenType(pref.getString(MainActivity.PREF_ID_TOKEN_TYPE, ""))
.setMapId(Constants.MAPID_CEDARMAPS_STREETS)
.build();
CedarMaps cedarMaps = new CedarMapsFactory(configuration).getInstance();
searchResult = cedarMaps.geocode(params[0], "tehran", 35.6961, 51.4231, 3000,
5);
} catch (CedarMapsException e) {
e.printStackTrace();
}
return searchResult;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
mProgress.dismiss();
try {
String status = jsonObject.getString("status");
if (status.equals("OK")) {
JSONArray array = jsonObject.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String[] location = item.getJSONObject("location").getString("center")
.split(",");
LatLng latLng = new LatLng(Double.parseDouble(location[0]),
Double.parseDouble(location[1]));
Marker marker = new Marker(mapView, item.getString("name"), "", latLng);
marker.setIcon(
new Icon(getActivity(), Icon.Size.MEDIUM, "marker-stroked",
"FF0000"));
mapView.addMarker(marker);
}
} else if (status.equals("ZERO_RESULTS")) {
Toast.makeText(getActivity(), getString(R.string.no_results),
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getActivity(), getString(R.string.unkonown_error),
Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), getString(R.string.parse_error),
Toast.LENGTH_LONG).show();
}
}
}
}
package com.cedarstudios.cedarmaps.sample.fragment;
import com.cedarstudios.cedarmaps.sample.Constants;
import com.cedarstudios.cedarmaps.sample.MainActivity;
import com.cedarstudios.cedarmaps.sample.R;
import com.cedarstudios.cedarmapssdk.CedarMaps;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
import com.cedarstudios.cedarmapssdk.CedarMapsFactory;
import com.cedarstudios.cedarmapssdk.config.Configuration;
import com.cedarstudios.cedarmapssdk.config.ConfigurationBuilder;
import com.cedarstudios.cedarmapssdk.tileprovider.CedarMapsTileLayer;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.MapView;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class APIGeocodeTestFragment extends Fragment implements View.OnClickListener {
private EditText mSearchEditText;
private MapView mapView;
private ArrayList<Marker> mMarkers = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_search, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
String accessToken = pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, "");
mapView.setAccessToken(accessToken);
CedarMapsTileLayer cedarMapsTileLayer = new CedarMapsTileLayer(Constants.MAPID_CEDARMAPS_STREETS);
mapView.setTileSource(cedarMapsTileLayer);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mapView.setZoom(12);
view.findViewById(R.id.search).setOnClickListener(this);
mSearchEditText = (EditText) view.findViewById(R.id.term);
mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
view.findViewById(R.id.search).performClick();
return true;
}
return false;
}
});
return view;
}
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mSearchEditText.getText().toString())) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
clearMarkers();
new SearchAsyncTask().execute(mSearchEditText.getText().toString().trim());
}
}
private void clearMarkers() {
for (Marker marker : mMarkers) {
mapView.removeMarker(marker);
}
mapView.setZoom(12);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mMarkers.clear();
mapView.clear();
}
class SearchAsyncTask extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog mProgress;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress = new ProgressDialog(getActivity());
mProgress.setMessage(getString(R.string.searching));
mProgress.show();
}
@Override
protected JSONObject doInBackground(String... params) {
JSONObject searchResult = null;
try {
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
Configuration configuration = new ConfigurationBuilder()
.setOAuth2AccessToken(pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, ""))
.setOAuth2TokenType(pref.getString(MainActivity.PREF_ID_TOKEN_TYPE, ""))
.setMapId(Constants.MAPID_CEDARMAPS_STREETS)
.build();
CedarMaps cedarMaps = new CedarMapsFactory(configuration).getInstance();
searchResult = cedarMaps.geocode(params[0]);
} catch (CedarMapsException e) {
e.printStackTrace();
}
return searchResult;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
mProgress.dismiss();
try {
String status = jsonObject.getString("status");
if (status.equals("OK")) {
JSONArray array = jsonObject.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String[] location = item.getJSONObject("location").getString("center")
.split(",");
LatLng latLng = new LatLng(Double.parseDouble(location[0]),
Double.parseDouble(location[1]));
Marker marker = new Marker(mapView, item.getString("name"), "", latLng);
marker.setIcon(
new Icon(getActivity(), Icon.Size.MEDIUM, "marker-stroked",
"FF0000"));
mapView.addMarker(marker);
}
} else if (status.equals("ZERO_RESULTS")) {
Toast.makeText(getActivity(), getString(R.string.no_results),
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getActivity(), getString(R.string.unkonown_error),
Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), getString(R.string.parse_error),
Toast.LENGTH_LONG).show();
}
}
}
}
package com.cedarstudios.cedarmaps.sample.fragment;
import com.cedarstudios.cedarmaps.sample.Constants;
import com.cedarstudios.cedarmaps.sample.MainActivity;
import com.cedarstudios.cedarmaps.sample.R;
import com.cedarstudios.cedarmapssdk.CedarMaps;
import com.cedarstudios.cedarmapssdk.CedarMapsException;
import com.cedarstudios.cedarmapssdk.CedarMapsFactory;
import com.cedarstudios.cedarmapssdk.config.Configuration;
import com.cedarstudios.cedarmapssdk.config.ConfigurationBuilder;
import com.cedarstudios.cedarmapssdk.tileprovider.CedarMapsTileLayer;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.MapView;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class APIReverseGeocodeTestFragment extends Fragment implements View.OnClickListener {
private EditText mSearchEditText;
private MapView mapView;
private ArrayList<Marker> mMarkers = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_search, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
String accessToken = pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, "");
mapView.setAccessToken(accessToken);
CedarMapsTileLayer cedarMapsTileLayer = new CedarMapsTileLayer(Constants.MAPID_CEDARMAPS_STREETS);
mapView.setTileSource(cedarMapsTileLayer);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mapView.setZoom(12);
view.findViewById(R.id.search).setOnClickListener(this);
mSearchEditText = (EditText) view.findViewById(R.id.term);
mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
view.findViewById(R.id.search).performClick();
return true;
}
return false;
}
});
mSearchEditText.setText("35.759926, 51.432512");
return view;
}
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(mSearchEditText.getText().toString())) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
clearMarkers();
new ReverseGeocodeAsyncTask().execute(mSearchEditText.getText().toString().trim());
}
}
private void clearMarkers() {
for (Marker marker : mMarkers) {
mapView.removeMarker(marker);
}
mapView.setZoom(12);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mMarkers.clear();
mapView.clear();
}
class ReverseGeocodeAsyncTask extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog mProgress;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress = new ProgressDialog(getActivity());
mProgress.setMessage(getString(R.string.searching));
mProgress.show();
}
@Override
protected JSONObject doInBackground(String... params) {
JSONObject searchResult = null;
try {
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
Configuration configuration = new ConfigurationBuilder()
.setOAuth2AccessToken(pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, ""))
.setOAuth2TokenType(pref.getString(MainActivity.PREF_ID_TOKEN_TYPE, ""))
.setMapId(Constants.MAPID_CEDARMAPS_STREETS)
.build();
CedarMaps cedarMaps = new CedarMapsFactory(configuration).getInstance();
String[] latlng = params[0].split(",");
searchResult = cedarMaps.geocode(Double.parseDouble(latlng[0]),
Double.parseDouble(latlng[1]));
} catch (CedarMapsException e) {
e.printStackTrace();
}
return searchResult;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
mProgress.dismiss();
try {
String status = jsonObject.getString("status");
if (status.equals("OK")) {
String address = jsonObject
.getJSONObject("result")
.getString("address");
String[] latlng = mSearchEditText.getText().toString().trim().split(",");
Marker marker = new Marker(mapView, address, "",
new LatLng(Double.parseDouble(latlng[0]),
Double.parseDouble(latlng[1])));
marker.setIcon(
new Icon(getActivity(), Icon.Size.MEDIUM, "marker-stroked",
"000FFF"));
mapView.addMarker(marker);
Toast.makeText(getActivity(), address,
Toast.LENGTH_LONG)
.show();
} else if (status.equals("ZERO_RESULTS")) {
Toast.makeText(getActivity(), getString(R.string.no_results),
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getActivity(), getString(R.string.unkonown_error),
Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), getString(R.string.parse_error),
Toast.LENGTH_LONG).show();
}
}
}
}
package com.cedarstudios.cedarmaps.sample.fragment;
import com.cedarstudios.cedarmaps.sample.Constants;
import com.cedarstudios.cedarmaps.sample.MainActivity;
import com.cedarstudios.cedarmaps.sample.R;
import com.cedarstudios.cedarmapssdk.tileprovider.CedarMapsTileLayer;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.ItemizedIconOverlay;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.MapView;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
public class ItemizedIconOverlayTestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
MapView mapView = (MapView) view.findViewById(R.id.mapView);
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
String accessToken = pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, "");
mapView.setAccessToken(accessToken);
CedarMapsTileLayer cedarMapsTileLayer = new CedarMapsTileLayer(Constants.MAPID_CEDARMAPS_STREETS);
mapView.setTileSource(cedarMapsTileLayer);
mapView.setCenter(new LatLng(35.763269, 51.431954));
mapView.setZoom(15);
ArrayList<Marker> markers = new ArrayList<Marker>();
markers.add(new Marker(mapView, getString(R.string.haghani_metro), null,
new LatLng(35.759926, 51.432512)));
markers.add(new Marker(mapView, getString(R.string.third_street), null,
new LatLng(35.762329, 51.429722)));
markers.add(new Marker(mapView, getString(R.string.haghani_way), null,
new LatLng(35.759055, 51.427362)));
markers.add(new Marker(mapView, getString(R.string.tabrizian), null,
new LatLng(35.762538, 51.435173)));
for (Marker marker : markers) {
marker.setIcon(new Icon(getActivity(), Icon.Size.MEDIUM, "marker-stroked", "#068a0a"));
}
mapView.addItemizedOverlay(new ItemizedIconOverlay(getActivity(), markers,
new ItemizedIconOverlay.OnItemGestureListener<Marker>() {
@Override
public boolean onItemSingleTapUp(int i, Marker marker) {
Toast.makeText(getActivity(), marker.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onItemLongPress(int i, Marker marker) {
Toast.makeText(getActivity(), marker.getTitle(), Toast.LENGTH_LONG).show();
return true;
}
}));
return view;
}
}
package com.cedarstudios.cedarmaps.sample.fragment;
import com.cedarstudios.cedarmaps.sample.Constants;
import com.cedarstudios.cedarmaps.sample.MainActivity;
import com.cedarstudios.cedarmaps.sample.R;
import com.cedarstudios.cedarmapssdk.tileprovider.CedarMapsTileLayer;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.views.MapView;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainTestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
String accessToken = pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, "");
MapView mapView = (MapView) view.findViewById(R.id.mapView);
mapView.setAccessToken(accessToken);
CedarMapsTileLayer cedarMapsTileLayer = new CedarMapsTileLayer(Constants.MAPID_CEDARMAPS_STREETS);
mapView.setTileSource(cedarMapsTileLayer);
mapView.setCenter(new LatLng(35.6961, 51.4231)); // center of tehran
mapView.setZoom(12);
return view;
}
}
package com.cedarstudios.cedarmaps.sample.fragment;
import com.cedarstudios.cedarmaps.sample.Constants;
import com.cedarstudios.cedarmaps.sample.MainActivity;
import com.cedarstudios.cedarmaps.sample.R;
import com.cedarstudios.cedarmapssdk.tileprovider.CedarMapsTileLayer;
import com.mapbox.mapboxsdk.api.ILatLng;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.Icon;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.views.MapController;
import com.mapbox.mapboxsdk.views.MapView;
import com.mapbox.mapboxsdk.views.MapViewListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MarkersTestFragment extends Fragment implements MapViewListener {
private MapView mapView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
SharedPreferences pref = getActivity().getSharedPreferences(MainActivity.PREF_NAME,
Context.MODE_PRIVATE);
String accessToken = pref.getString(MainActivity.PREF_ID_ACCESS_TOKEN, "");
mapView.setAccessToken(accessToken);
CedarMapsTileLayer cedarMapsTileLayer = new CedarMapsTileLayer(Constants.MAPID_CEDARMAPS_STREETS);
mapView.setTileSource(cedarMapsTileLayer);
mapView.setCenter(new LatLng(35.703859, 51.408037));
mapView.setZoom(14);
LatLng position = new LatLng(35.709086, 51.401471);
addMarker(position);
position = new LatLng(35.699781, 51.397565);
addMarker(position);
position = new LatLng(35.705636, 51.414174);
addMarker(position);
position = new LatLng(35.698631, 51.407693);
addMarker(position);
mapView.setMapViewListener(this);
return view;
}
public void addMarker(LatLng position) {
Marker marker = new Marker(mapView, "", "", position);
marker.setIcon(new Icon(getActivity(), Icon.Size.SMALL, "marker-stroked", "FF0000"));
mapView.addMarker(marker);
}
@Override
public void onShowMarker(MapView mapView, Marker marker) {
}
@Override
public void onHideMarker(MapView mapView, Marker marker) {
}
@Override
public void onTapMarker(MapView mapView, Marker marker) {
MapController mapController = new MapController(mapView);
mapController.animateTo(marker.getPoint());
}
@Override
public void onLongPressMarker(MapView mapView, Marker marker) {
}
@Override
public void onTapMap(MapView mapView, ILatLng iLatLng) {
}
@Override
public void onLongPressMap(MapView mapView, ILatLng iLatLng) {
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#fff"
android:background="#00000000"
android:minHeight="24dp"
android:textSize="20sp" />
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.mapbox.mapboxsdk.views.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp">
<ImageButton
android:id="@+id/search"
android:layout_width="48dp"
android:layout_height="48dp"
android:padding="5dp"
android:src="@drawable/ic_search" />
<EditText
android:id="@+id/term"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:imeOptions="actionSearch"
android:layout_margin="5dp"
android:hint="جستجو برای..." />
</LinearLayout>
<ListView
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.mapbox.mapboxsdk.views.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">CedarMaps Sample</string>
<string name="action_settings">Settings</string>
<string name="mainTestMap">Main Test Map</string>
<string name="markersTestMap">Markers Test</string>
<string name="itemizedOverlayTestMap">ItemizedIconOverlay</string>
<string name="searchAPI">Geocode API</string>
<string name="streetSearchAPIAdvanced">Advanced Geocode API</string>
<string name="reverseGeocode">Reverse geocode API</string>
<string name="drawerOpen">Open Nav Drawer</string>
<string name="drawerClose">Close Nav Drawer</string>
<string name="haghani_metro">مترو شهید حقانی</string>
<string name="third_street">خیابان سوم</string>
<string name="haghani_way">بزرگراه حقانی</string>
<string name="tabrizian">خیابان تبریزیان</string>
<string name="searching">در حال جستجو...</string>
<string name="unkonown_error">خطایی پیش آمد</string>
<string name="no_results">نتیجه‌ای یافت نشد</string>
<string name="parse_error">خطای پردازش نتیجه</string>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
## Getting started with the CedarMaps Android SDK
This guide will take you through the process of adding a map to your Android app.
### Installation
To install the current stable version add this to your build.gradle:
To install the current **stable** version add this to your `build.gradle`:
```groovy
repositories {
maven {
url "http://repo.cedarmaps.com/android/"
}
}
dependencies {
compile('com.cedarmaps:CedarMapsSDK:0.7.0@aar') {
transitive = true
}
}
```
### Required Permissions
Ensure the following *core* permissions are requested in your `AndroidManifest.xml` file:
```xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
If your project needs to access location services, it'll also need the following permissions too:
```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
```
### Getting Access Token
In order to use CedarMaps API and TileSource you should get `AccessToken` with your client id and
client secret:
```java
com.cedarstudios.cedarmapssdk.config.Configuration
configuration = new ConfigurationBuilder()
.setClientId(clientId)
.setClientSecret(clinetSecret)
.build();
CedarMapsFactory factory = new CedarMapsFactory(configuration);
CedarMaps cedarMaps = factory.getInstance();
OAuth2Token oAuth2Token = cedarMaps.getOAuth2Token();
```
Then you should use `oAuth2Token.getAccessToken()` in mapView or API
### The MapView
This project is based on [Mapbox Android SDK](https://www.mapbox.com/mapbox-android-sdk/) and provides
CedarMapsTileLayer and extra API over Mapbox.
The `MapView` class is the key component of this library. It behaves
like any other `ViewGroup` and its behavior can be changed statically with an
[XML layout](http://developer.android.com/guide/topics/ui/declaring-layout.html)
file, or programmatically during runtime.
#### XML layout
To add the `MapView` as a layout element, add the following to your xml file:
```xml
<com.mapbox.mapboxsdk.views.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
```
And then you can call it programmatically with
```java
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setAccessToken(accessToken);
```
#### On runtime
On runtime you can create a new MapView by specifying the context of the
application and then use `CedarMapsTileLayer` as tile source.
```java
MapView mapView = new MapView(context);
mapView.setAccessToken(accessToken);
mapView.setTileSource(new CedarMapsTileLayer(mapId));
```
Currently you can use `cedarmaps.streets` as default mapId
### Attention
currently CedarMaps supports Tehran city. so be sure that you handle the map screen limit by the
boundingBox and the default map center location:
```java
// center of tehran
mapView.setCenter(new LatLng(35.6961, 51.4231));
// limit scrollable area
mapView.setScrollableAreaLimit(new BoundingBox(north, east, south, west));
```
### Overlays
Anything visual that is displayed over the map, maintaining its geographical
position, we call it an `Overlay`. To access a MapView's overlays
at any point during runtime, use:
```java
mapView.getOverlays();
```
#### Markers
Adding a marker with the default styling is as simple as calling this
for every marker you want to add:
```java
Marker marker = new Marker(mapView, title, description, LatLng)
mapView.addMarker(marker);
```
#### Location overlay
The location of the user can be displayed on the view using `UserLocationOverlay`
```java
GpsLocationProvider myLocationProvider = new GpsLocationProvider(getActivity());
UserLocationOverlay myLocationOverlay = new UserLocationOverlay(myLocationProvider, mapView);
myLocationOverlay.enableMyLocation();
myLocationOverlay.setDrawAccuracyEnabled(true);
mapView.getOverlays().add(myLocationOverlay);
```
#### Paths
Paths are treated as any other `Overlay`, and are drawn like this:
```java
PathOverlay line = new PathOverlay(Color.RED, this);
line.addPoint(new LatLng(51.2, 0.1));
line.addPoint(new LatLng(51.7, 0.3));
mapView.getOverlays().add(line);
```
#### Drawing anything into the map
To add anything with a higher degree of customization you can declare your own `Overlay`
subclass and define what to draw by overriding the `draw` method. It will
give you a Canvas object for you to add anything to it:
```java
class AnyOverlay extends Overlay{
@Override
protected void draw(Canvas canvas, MapView mapView, boolean shadow) {
//do anything with the Canvas object
}
}
```
### Screen rotation
By default, every time the screen is rotated, Android will call `onCreate`
and return all states in the app to their inital values. This includes current
zoom level and position of the MapView. The simplest way to avoid this is adding
this line to your `AndroidManifest.xml`, inside `<activity>`:
android:configChanges="orientation|screenSize|uiMode"
Alternatively you can override the methods `onSaveInstanceState()` and
`onRestoreInstanceState()` to have broader control of the saved states in the app.
See this [StackOverflow question](http://stackoverflow.com/questions/4096169/onsaveinstancestate-and-onrestoreinstancestate) for
more information on these methods
=======
### CedarMaps API
In addition to use MapView, you can use CedarMaps API to retrieve location based data and street search.
Before beginning to call CedarMaps API you should get `AccessToken` with your client id and client secret
```java
com.cedarstudios.cedarmapssdk.config.Configuration
configuration = new ConfigurationBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.build();
CedarMapsFactory factory = new CedarMapsFactory(configuration);
CedarMaps cedarMaps = factory.getInstance();
OAuth2Token oAuth2Token = cedarMaps.getOAuth2Token();
```
Then you should use `oAuth2Token` with each API call
#### Geocode (Street Search)
For finding a street you can easily call streetSearch method.
```java
Configuration configuration = new ConfigurationBuilder()
.setOAuth2AccessToken(oAuth2Token.getAccessToken())
.setOAuth2TokenType(oAuth2Token.getTokenType())
.setMapId(Constants.MAPID_CEDARMAPS_STREETS)
.build();
CedarMaps cedarMaps = new CedarMapsFactory(configuration).getInstance();
searchResult = cedarMaps.geocode(searchTerm);
```
The output would be something like this for search term "همت":
```json
{
"results": [
{
"address": "المهدی",
"id": 301568,
"location": {
"bb": {
"ne": "35.770861600000003,51.323841700000003",
"sw": "35.770540400000002,51.323066400000002"
},
"center": "35.770585227006897,51.323426168064202"
},
"name": "همت",
"type": "street"
},
{
"address": "کاظم آباد,مهران,اراضی عباس آباد,...",
"id": 397432,
"location": {
"bb": {
"ne": "35.759246099999999,51.4836156",
"sw": "35.7491463,51.423702800000001"
},
"center": "35.749153889854,51.427947792189102"
},
"name": "همت",
"type": "expressway"
},
{
"address": "ابوذر,شهرابی",
"id": 312434,
"location": {
"bb": {
"ne": "35.679308300000002,51.480144099999997",
"sw": "35.679143099999997,51.478227199999999"
},
"center": "35.679225700000003,51.479185649999998"
},
"name": "همتی",
"type": "street"
}
],
"status": "OK"
}
```
More advanced street searches are available in sample app;
#### Reverse Geocode
You can retrieve data about a location by using reverse geocode API
```java
Configuration configuration = new ConfigurationBuilder()
.setOAuth2AccessToken(oAuth2Token.getAccessToken())
.setOAuth2TokenType(oAuth2Token.getTokenType())
.build();
CedarMaps cedarMaps = new CedarMapsFactory(configuration).getInstance();
searchResult = cedarMaps.geocode(lat, lng);
```
The output would be something like this for 35.4,52.3:
```json
{
"result": {
"address": "تهران، شهرک غرب، خیابان دادمان، خیابان سپهر",
"city": "تهران",
"components": [
{
"long_name": "خیابان سپهر",
"short_name": "سپهر",
"type": "street"
},
{
"long_name": "خیابان دادمان",
"short_name": "دادمان",
"type": "steet"
},
{
"long_name": "شهرک غرب",
"short_name": "شهرک غرب",
"type": "locality"
}
],
"locality": "شهرک غرب"
},
"status": "OK"
}
```
### More Examples Via TestApp
The CedarMaps Android SDK is actually an [Android Library Module](https://developer.android.com/tools/projects/index.html#LibraryModules),
which means in order to test it out in an emulator or a device during development a [Test Module](https://developer.android.com/tools/projects/index.html#testing) is needed. We call this test module
the **TestApp**. It contains many different examples of new functionality or just ways to do certain things. We highly recommend checking it out.
The source code for these tests / examples is located under the CedarMapsTestApp directory.
You can find more useful examples on [Mapbox SDK Test App](https://github.com/mapbox/mapbox-android-sdk/tree/mb-pages/MapboxAndroidSDKTestApp)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
start ConEmu64.exe /cmdlist ^> "%ProgramFiles(x86)%\Git\bin\sh.exe" --login -i
\ No newline at end of file
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
\ No newline at end of file
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
include ':CedarMapsTestApp', ':CedarMapsSDK'
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment