I'm using for first time the DirectionsManager to create routes in Bing Maps AJAX v7. The route is created correctly, but comes with two small "infoboxes" showing "A" at the start of the route, and "B" at the final. I want to remove those infoboxes, but honestly, after reading all the documentation (http://msdn.microsoft.com/en-us/library/hh312832.aspx) and "Binging/Googling" a while, I can't found anything helpful. Also, I tried every option inside setRenderOptions. Any ideas?
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
directionsManager.resetDirections();
directionsManager.setRenderOptions({autoDisplayDisambiguation: false,
autoUpdateMapView: true, displayManeuverIcons: false, displayPreItineraryItemHints: false, displayPostItineraryItemHints: false, displayRouteSelector: false, displayStepWarnings: false, drivingPolylineOptions: { strokeColor: new Microsoft.Maps.Color(150, 255, 51, 51), strokeThickness: 8 }
});
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: '000 fake street, Houston TX 77000' });
directionsManager.addWaypoint(seattleWaypoint);
var tacomaWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: '111 fake street, Houston TX 77111' });
directionsManager.addWaypoint(tacomaWaypoint);
directionsManager.calculateDirections();
One possible solution is to customize the pushpin to display blank pushpin with a small size (I've tried with another pushpin with 15x15 pixels size):
// Set the render options
directionsManager.setRenderOptions({
itineraryContainer: document.getElementById('itineraryDiv'),
displayWalkingWarning: false,
walkingPolylineOptions:{strokeColor: new Microsoft.Maps.Color(200, 0, 255, 0)},
waypointPushpinOptions: {icon:'pin_blank.png', height:1, width:1}
});
The other way might consist in calling the service by yourself and handling the request and response in your code. Here is an example: http://msdn.microsoft.com/en-us/library/gg427607.aspx
Here is the code that might be what you will help you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
function GetMap()
{
// Initialize the map
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road });
}
function ClickRoute(credentials)
{
map.getCredentials(MakeRouteRequest);
}
function MakeRouteRequest(credentials)
{
var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + document.getElementById('txtStart').value + "&wp.1=" + document.getElementById('txtEnd').value + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
CallRestService(routeRequest);
}
function RouteCallback(result) {
if (result &&
result.resourceSets &&
result.resourceSets.length > 0 &&
result.resourceSets[0].resources &&
result.resourceSets[0].resources.length > 0) {
// Set the map view
var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
map.setView({ bounds: viewBoundaries});
// Draw the route
var routeline = result.resourceSets[0].resources[0].routePath.line;
var routepoints = new Array();
for (var i = 0; i < routeline.coordinates.length; i++) {
routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
}
// Draw the route on the map
var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});
map.entities.push(routeshape);
}
}
function CallRestService(request)
{
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
</script>
</head>
<body onload="GetMap();">
<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>
<input id="txtStart" type="text" value="Seattle"/>
<input id="txtEnd" type="text" value="Portland"/>
<input type="button" value="Calculate Route" onclick="ClickRoute()"/>
</body>
</html>
Related
I am working on a simple Google Maps app using the KnockoutJS library - or at least it seemed simple enough in concept.
After reading up on KnockoutJS and working out some examples, I put together the initial parts. The html so far is just the map, I aim to populate the list as soon as I get over the first hurdle. The hurdle is in the Javascript. Here is the code for reference:
"use strict";
var map;
var center;
var defaultBounds;
var placesServices;
//LocationObject created to hold data for locations generated from google.places.nearbySearch
var LocationObject = function(data){
this.position = data.geometry.location;
this.lat = data.geometry.location.lat;
this.lng = data.geometry.location.lng;
this.name = data.name;
this.placeID = data.place_id;
this.rating = data.rating;
this.types = data.types;
this.linkToPhoto = data.html_attributions;
};
function initMap(){
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 17,
mapTypeId: 'satellite',
draggable: true,
zoomControl: false,
scrollwheel: true,
disableDoubleClickZoom: true
});
defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(47.614217, -122.317981),new google.maps.LatLng(47.612975, -122.316291));
map.fitBounds(defaultBounds);
placesServices = new google.maps.places.PlacesService(map);
}
//ViewModel created to observe changes on the map
var MapViewModel = function(){
var self = this;
self.testarr = ko.observableArray([
{ firstName: 'Bert', lastName: 'Bertington' },
{ firstName: 'Charles', lastName: 'Charlesforth' },
{ firstName: 'Denise', lastName: 'Dentiste' }
]);
self.locations = ko.observableArray([]);
self.markers = [];
this.getNearbyLocations = function(){
if(placesServices === undefined){
placesServices = new google.maps.places.PlacesService(map);
}
var request = {
location: center,
radius: getBoundsRadius(defaultBounds),
type: ['establishment']
};
placesServices.nearbySearch(request, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i <= 18; i++) {
var marker = new google.maps.Marker({
map: map,
position: results[i].geometry.location,
animation: google.maps.Animation.DROP
});
self.locations.push(new LocationObject(results[i]));
self.markers.push(marker);
}
} else{
alert("We were not able to find any nearby locations in this Neighbourhood.");
}
});
};
this.init = function(){
self.getNearbyLocations();
};
};
var myMapViewModel = new MapViewModel();
myMapViewModel.init();
ko.applyBindings(myMapViewModel);
/* Utility Functions */
function getBoundsRadius(bounds){....}
The error is:
Uncaught ReferenceError: google is not defined
at MapViewModel.getNearbyLocations
and I don't get why it's not being recognized here, when the map itself loads first without issue but here it get's hung up.
Here is the html for reference, but there shouldn't be an issue there:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Per Google guideline scheduled for the M65 release, css has been moved to an importer -->
<link rel="import" href="importer.htm"></link>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-md-4">
<!-- List goes in this column. -->
</div>
</div>
<div class="col-xs-12 col-md-8">
<!-- Map goes into this column. -->
<div id="map" style="width:100%;height:100vh;"></div>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<!-- Optional JavaScript -->
<script src="js/knockout.js" ></script>
<script src="js/app.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC-1EdIyUOb74oGG_mEoPvJTAGCSJvSQms&callback=initMap&libraries=places"></script>
</body>
I also thought that the error was because your app.js is being called before the maps script. But I tried changing it, same error, and I also tried removing the async parameter (as suggested by user3297291's comment), still the same error. Theoretically it should have worked.
But this worked - wrap the last 3 lines of your app.js code inside a ready() function:
$(document).ready(function(){
var myMapViewModel = new MapViewModel();
myMapViewModel.init();
ko.applyBindings(myMapViewModel);
});
I 'm having issues adding in a search widget to a shortlist application. I have included the code below. The search bar shows up, but is not functional.
I am needing to have this to where it can search business names that are included within the application.
<html>
<head>
<title>ChahtaPreneur</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link type="image/ico" rel="shortcut icon" href="//resources.esri.com/favicon.ico">
<link type="image/ico" rel="icon" href="//resources.esri.com/favicon.ico">
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<script src="https://js.arcgis.com/3.18/"></script>
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.2/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/esri/css/esri.css">
<link rel="stylesheet" type="text/css" href="colorbox/colorbox.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="lib/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="lib/common/helper_functions.js"></script>
<script type="text/javascript">var djConfig = {parseOnLoad: true};</script>
<script type="text/javascript" src="colorbox/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="lib/jquery.animate-colors-min.js"></script>
<script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/"></script>
<style>
html,body,
#mapDiv,.map.container{
padding:0;
margin:0;
height:100%;
}
#search {
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 720px;
}
</style>
<script src="https://js.arcgis.com/3.18/"></script>
<!--
To correctly reference your Shortlist in search engine:
- create and fill out extensively an ArcGIS Online item that link to your final application
- edit the following four tags as well as the title tag above on line 4
-->
<meta name="description" content="This story map was created with the Story Map Shortlist application in ArcGIS Online.">
<!-- Facebook sharing -->
<meta property="og:type" content="article"/>
<meta property="og:title" content="Story Map Shortlist"/>
<meta property="og:description" content="This story map was created with the Story Map Shortlist application in ArcGIS Online."/>
<meta property="og:image" content="resources/common/icons/esri-globe.png"/>
<!--
This application is released under the Apache License V2.0 by Esri http://www.esri.com/
Checkout the project repository on GitHub to access source code, latest revision, developer documentation, FAQ and tips
https://github.com/Esri/shortlist-storytelling-template-js
-->
<script type="text/javascript">
//-------------------------------------------------------------------------------------------
// Application configuration (ignored on ArcGIS Online, Portal and during development)
//-------------------------------------------------------------------------------------------
var configOptions = {
// Enter an application ID created through the Shortlist builder
appid: "f8c9b5d9a2c64703bb72910f46f59d7c",
// Optionally to secure Shortlist's access, use an OAuth application ID (example: 6gyOg377fLUhUk6f)
// User will need to sign-in to access the viewer even if your application is public
oAuthAppId: "",
// Optionally to be able to use the appid URL parameter, configure here the list of application author
// whose application are allowed to be viewed by this Shortlist deployment
// This is the Portal username of the Shortlist owner (e.g. ["user1"], ["user1", "user2"])
authorizedOwners: ["*"]
};
// Optionally sharing and proxy URLs can be configured in app/config.js. This is only required
// when the webmap is not hosted on ArcGIS Online or a Portal for ArcGIS instance and the application isn't deployed as /home/Shortlist/ or /apps/Shortlist/.
// Optionally Bing Maps key, Geometry and Geocode service's URLs can be configured in app/config.js. This is only required
// if the Organization or Portal for ArcGIS instance default configuration has to be overwritten.
</script>
<script type="text/javascript">
dojo.require("dijit.dijit");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.map");
dojo.require("esri.arcgis.utils");
dojo.require("esri.dijit.Geocoder");
/******************************************************
******************** config section ******************
*******************************************************/
var WEBMAP_ID = "6b3d1da24e5841f1b8d47de63b7be7a4";
var BOOKMARKS_ALIAS = "Zoom";
var COLOR_ORDER = "green,red,blue,purple"; // will only use as many colors as you have content (point) layers
var BINGMAPS_KEY = "";
/******************************************************
******************** app variables ********************
*******************************************************/
var _contentLayers = [];
var _isMobile = isMobile();
var _map;
var _bookmarks;
var _layerCurrent;
var _selected;
var _initExtent;
var _dojoReady = false;
var _jqueryReady = false;
var geocoder;
var locatorUrl = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/";
/******************************************************
************************* init ************************
*******************************************************/
dojo.addOnLoad(function() {_dojoReady = true;init()});
jQuery(document).ready(function() {_jqueryReady = true;init()});
/* init comes in two parts because of async call to
createMap. */
function init() {
if (!_jqueryReady) return;
if (!_dojoReady) return;
if (getParameterByName("webmap") != "") {
WEBMAP_ID = getParameterByName("webmap");
}
if (getParameterByName("bookmarks_alias") != "") {
BOOKMARKS_ALIAS = getParameterByName("bookmarks_alias");
}
if (getParameterByName("color_order") != "") {
COLOR_ORDER = getParameterByName("color_order")
}
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▼');
$(this).resize(handleWindowResize);
$("#zoomIn").click(function(e) {
_map.setLevel(_map.getLevel()+1);
});
$("#zoomOut").click(function(e) {
_map.setLevel(_map.getLevel()-1);
});
$("#zoomExtent").click(function(e) {
_map.setExtent(_initExtent);
});
$(document).bind('cbox_complete', function(){
$(".details .rightDiv").height($(".details").height() - 65);
});
$("#bookmarksToggle").click(function(){
if ($("#bookmarksDiv").css('display')=='none'){
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▲');
}
else{
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▼');
}
$("#bookmarksDiv").slideToggle();
});
var mapDeferred = esri.arcgis.utils.createMap(WEBMAP_ID, "map", {
mapOptions: {
slider: false,
wrapAround180:false
},
ignorePopups: true,
bingMapsKey: BINGMAPS_KEY
});
mapDeferred.addCallback(function(response) {
document.title = response.itemInfo.item.title;
$("#title").html(response.itemInfo.item.title);
$("#subtitle").html(response.itemInfo.item.snippet);
_map = response.map;
//resize the map when the browser resizes
dojo.connect(dijit.byId('map'), 'resize', _map,_map.resize);
dojo.connect(_map, 'onExtentChange', refreshList);
// click action on the map where there's no graphic
// causes a deselect.
dojo.connect(_map, 'onClick', function(event){
if (event.graphic == null) {
unselect();
}
});
_bookmarks = response.itemInfo.itemData.bookmarks;
if (_bookmarks) {
loadBookmarks();
$("#bookmarksCon").show();
}
var layers = response.itemInfo.itemData.operationalLayers;
if(_map.loaded){
initMap(layers);
} else {
dojo.connect(_map,"onLoad",function(){
initMap(layers);
});
}
});
mapDeferred.addErrback(function(error) {
console.log("Map creation failed: ", dojo.toJson(error));
});
}
function initMap(layers) {
var supportLayers = [];
var pointLayers = [""];
$.each(layers,function(index,value){
if (value.url == null) {
if (value.featureCollection.layers[0].featureSet.geometryType == "esriGeometryPoint") {
pointLayers.push(value);
} else {
supportLayers.push(value);
}
} else {
// if the layer has an url property (meaning that it comes from a service), just
// keep going...it will remain in the map, but won't be query-able.
}
});
_initExtent = _map.extent;
var supportLayer;
$.each(supportLayers,function(index,value) {
supportLayer = findLayer(_map,value.title);
if (supportLayer == null) return;
$.each(supportLayer.graphics,function(index,value) {
value.attributes.getValueCI = getValueCI; // assign extra method to handle case sensitivity
});
dojo.connect(supportLayer, "onMouseOver", baselayer_onMouseOver);
dojo.connect(supportLayer, "onMouseOut", baselayer_onMouseOut);
dojo.connect(supportLayer, "onClick", baselayer_onClick);
});
if (COLOR_ORDER.split(",").length < pointLayers.length) {
// you have supplied fewer colors than point layers and
// therefore have lost your sorting privileges...
colorschemes = COLOR_SCHEMES;
} else {
// sort the colors
var colorschemes = getSortedColorSchemes();
// burn off any extra colors, if you have more colors
// than points.
while (pointLayers.length < colorschemes.length) {
colorschemes.shift()
};
}
var contentLayer;
$.each(pointLayers,function(index,value) {
_map.removeLayer(findLayer(_map,value.title));
if (index <= 4) { // maximum of 4 point layers.
$.each(value.featureCollection.layers[0].featureSet.features,function(index,value) {
value.attributes.getValueCI = getValueCI; // assign extra method to handle case sensitivity
});
contentLayer = buildLayer(
value.featureCollection.layers[0].featureSet.features.sort(SortByID),
colorschemes[index].iconDir,
colorschemes[index].iconPrefix
);
contentLayer.color = colorschemes[index].color;
contentLayer.title = value.title;
dojo.connect(contentLayer, "onMouseOver", layer_onMouseOver);
dojo.connect(contentLayer, "onMouseOut", layer_onMouseOut);
dojo.connect(contentLayer, "onClick", layer_onClick);
_map.addLayer(contentLayer);
_contentLayers.push(contentLayer);
}
});
_contentLayers.reverse();
$.each(_contentLayers,function(index,value){
$("#tabs").append('<div class="tab" onclick="activateLayer(_contentLayers['+index+'])">'+value.title+'</div>');
});
activateLayer(_contentLayers[0]);
dojo.connect(_map.infoWindow,"onHide",infoWindow_onHide);
handleWindowResize();
$("#zoomToggle").css("visibility","visible");
// Solomon Additions
// add a graphics layer for geocoding results
_map.addLayer(new esri.layers.GraphicsLayer({
id: "results"
}));
var myGeocoders = [{
url: locatorUrl,
name: "Single_Line"
}];
// create the geocoder
geocoder = new esri.dijit.Geocoder({
autoComplete : true,
autoNavigate: true,
localSearchOptions : {
minScale : 3,
distance : 4000},
maxLocations : 20,
arcgisGeocoder: false,
geocoders:myGeocoders,
value:'Search by Name',
map : _map
}, "search");
geocoder.startup();
geocoder.focus();
var symbol = new esri.symbol.PictureMarkerSymbol({
"angle":0,
"xoffset":0,
"yoffset":10,
"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png",
"contentType":"image/png",
"width":24,
"height":24
});
var template = new esri.InfoTemplate("${NAME}", "${*}");
dojo.connect(geocoder, "onFindResults", function(response) {
//STEVE CHANGES
//Use first match
//var name = response.results[0].name;
//Match name with locations layer and selected that index
//for(i in _locations){
//if(name === _locations[i].attributes.getName()){
//preSelection()
//_selected = _locations[i];
//postSelection();
//}
//}
//STEVE CHANGES END
console.log("find results: ", response);
var l = _map.getLayer("shortlistlayer");
l.clear();
_map.infoWindow.hide();
dojo.forEach(response.results, function(r) {
r.feature.attributes.NAME = r.NAME;
r.feature.setSymbol(symbol);
r.feature.setInfoTemplate(template);
l.add(r.feature);
});
});
// solomon Addition Ends
}
/******************************************************
******************** event handlers *******************
*******************************************************/
function tile_onMouseOver(e) {
$(this).stop().animate({'background-color' : COLOR_FULL});
}
function tile_onMouseOut(e) {
if (_selected != null) {
// does this tile represent the selected graphic?
var id = parseInt($(this).attr("id").substring(4));
if (_selected.attributes.getValueCI("Number") == id) {
return;
}
}
$(this).stop().animate({'background-color' : COLOR_DIM});
}
function tile_onClick(e) {
// turn off the last selected tile...
if (_selected != null) {
var tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0];
if ($(tile).attr("id") != $(this).attr("id")) $(tile).stop().animate({'background-color' : COLOR_DIM});
}
$(this).stop().animate({'background-color' : COLOR_FULL});
var id= $(this).attr("id").substring(4);
_selected = $.grep(_layerCurrent.graphics,function(n,i){return n.attributes.getValueCI("Number") == id})[0];
postSelection();
}
function infoWindow_onHide(event) {
unselect();
}
function baselayer_onMouseOver(event)
{
if (_isMobile) return;
_map.setMapCursor("pointer");
var graphic = event.graphic;
$("#hoverInfo").html(graphic.attributes.getValueCI("Title"));
var pt = event.screenPoint;
hoverInfoPos(pt.x,pt.y);
}
function baselayer_onMouseOut(event)
{
if (_isMobile) return;
_map.setMapCursor("default");
$("#hoverInfo").hide();
}
function baselayer_onClick(event) {
var feature = event.graphic;
_map.infoWindow.setTitle(event.graphic.attributes.getValueCI("NAME"));
_map.infoWindow.setContent(event.graphic.attributes.getValueCI("CAPTION")+"<p><span class='infoWindowLink'>Details >></span></p>");
_map.infoWindow.show(event.mapPoint);
$(".infoWindowLink").click(function(e) {
showDetails(feature);
});
$("#hoverInfo").hide();
}
function layer_onClick(event)
{
var tile;
if (_selected != null) {
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0]
$(tile).stop().animate({'background-color' : COLOR_DIM});
}
_selected = event.graphic;
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0]
$(tile).stop().animate({'background-color' : COLOR_FULL});
postSelection();
}
function layer_onMouseOver(event)
{
if (_isMobile) return;
_map.setMapCursor("pointer");
var graphic = event.graphic;
if (graphic == _selected) return;
graphic.setSymbol(graphic.symbol.setHeight(30).setWidth(24));
$("#hoverInfo").html(graphic.attributes.getValueCI("NAME"));
var pt = _map.toScreen(graphic.geometry);
hoverInfoPos(pt.x,pt.y);
}
function layer_onMouseOut(event)
{
if (_isMobile) return;
_map.setMapCursor("default");
var graphic = event.graphic;
graphic.setSymbol(graphic.symbol.setHeight(28).setWidth(22));
$("#hoverInfo").hide();
}
/******************************************************
****************** other functions ********************
*******************************************************/
function unselect() {
if (_selected != null) {
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0]
$(tile).stop().animate({'background-color' : COLOR_DIM});
}
_selected = null;
postSelection();
}
// sort items by numeric ID
function SortByID(a, b){
var aID = a.attributes.getValueCI("Number");
var bID = b.attributes.getValueCI("Number");
return ((aID < bID) ? -1 : ((aID > bID) ? 1 : 0));
}
function loadBookmarks() {
$.each(_bookmarks,function(index,value){$("#bookmarksDiv").append("<p><a>"+value.name+"</a></p>")});
$("#bookmarksDiv a").click(function(e) {
var name = $(this).html();
var extent = new esri.geometry.Extent($.grep(_bookmarks,function(n,i){return n.name == name})[0].extent);
_map.setExtent(extent);
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▼');
$("#bookmarksDiv").slideToggle();
});
}
function activateLayer(layer) {
_selected = null;
postSelection();
_layerCurrent = layer;
var tab = $.grep($(".tab"),function(n,i){return $(n).html() == _layerCurrent.title})[0];
$(".tab").removeClass("tab-selected");
$(tab).addClass("tab-selected");
$.each(_contentLayers,function(index,value){
value.setVisibility(value == _layerCurrent);
});
$("#myList").empty();
var display;
var tile;
var img;
var footer;
var num;
var title;
$.each(_layerCurrent.graphics,function(index,value){
if (_map.extent.contains(value.geometry)) {
display = "visible"
} else {
display = "none";
}
tile = $('<li id="item'+value.attributes.getValueCI("Number")+'" style="display:'+display+'">');
img = $('<img src="'+value.attributes.getValueCI("THUMB_URL")+'">');
footer = $('<div class="footer"></div>');
num = $('<div class="num" style="background-color:'+_layerCurrent.color+'">'+value.attributes.getValueCI("Number")+'</div>');
title = $('<div class="blurb">'+value.attributes.getValueCI("Name")+'</div>');
$(footer).append(num);
$(footer).append(title);
$(tile).append(img);
$(tile).append(footer);
$("#myList").append(tile);
});
// event handlers have to be re-assigned every time you load the list...
$("ul.tilelist li").mouseover(tile_onMouseOver);
$("ul.tilelist li").mouseout(tile_onMouseOut);
$("ul.tilelist li").click(tile_onClick);
$("ul.tilelist").animate({ scrollTop: 0 }, { duration: 200 } );
}
function refreshList() {
var tile;
$.each(_layerCurrent.graphics,function(index,value){
//find the corresponding tile
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+value.attributes.getValueCI("Number")})[0];
if (_map.extent.contains(value.geometry)) {
if ($(tile).css("display") == "none") $(tile).stop().fadeIn();
} else {
if ($(tile).css("display") != "none") $(tile).stop().fadeOut(1000);
}
});
}
function buildLayer(arr,iconDir,root) {
var layer = new esri.layers.GraphicsLayer();
var pt;
var sym;
$.each(arr,function(index,value){
pt = new esri.geometry.Point(value.geometry.x,value.geometry.y,value.geometry.spatialReference);
sym = new esri.symbol.PictureMarkerSymbol("images/icons/"+iconDir+"/"+root+value.attributes.getValueCI("Number")+".png",22,28);
layer.add(new esri.Graphic(pt,sym,value.attributes));
});
return layer;
}
function getValueCI(field) {
var found;
$.each(this,function(index,value){
if (index.toUpperCase() == field.toUpperCase()) {
found = index;
return false;
}
});
return this[found];
}
function handleWindowResize() {
var heightDoc = getViewportDimensions()[1];
$("#mainWindow").height(heightDoc - ($("#header").height()));
dijit.byId("mainWindow").layout();
$("#paneLeft").height($("#mainWindow").height() - 35);
$(".tilelist").height($("#paneLeft").height() - 20);
$("#map").height($("#mainWindow").height() - 35);
Well, I went though your code the major error i can see is that multiple define error.
Root Cause:
The main reason for it you are loading those libraries more than once who expose define.
Solution:
In your case i noticed you have loaded ArcGIS JS Api more than once.
Just load only one source of ArcGIS it should work.
One more thinh in attached code you are using multiple versions of CSS.
you are suppose to use same version of ESRI CSS which you are using for JS.
As per your code you are using legacy model of coding style so go for arcgis js api's that version only.
Code without multiple define error: https://jsfiddle.net/vikash2402/362ft9g7/
Hoping this will help you :)
Well, Here is the working code for esri search widget.
Just require the needed libraries and plugin the code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>Search with Suggestion Template</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.18/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<style>
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#search {
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 74px;
}
</style>
<script src="https://js.arcgis.com/3.18/"></script>
<script>
require([
"esri/map", "esri/dijit/Search", "esri/layers/FeatureLayer", "esri/InfoTemplate", "dojo/domReady!"
], function (Map, Search, FeatureLayer,InfoTemplate) {
var map = new Map("map", {
basemap: "gray",
center: [-82.93, 42.5], // lon, lat
zoom: 10
});
var search = new Search({
sources: [{
featureLayer: new FeatureLayer("https://services.arcgis.com/b6gLrKHqgkQb393u/arcgis/rest/services/TaxParcelQuery/FeatureServer/0", {
outFields: ["*"],
infoTemplate: new InfoTemplate("Parcels", "Owner name: ${OWNERNME1}</br>Parcel ID: ${PARCELID}</br>Site address: ${SITEADDRESS}")
}),
outFields: ["OWNERNME1","PARCELID","SITEADDRESS"],
displayField: "OWNERNME1",
suggestionTemplate: "${PARCELID}: ${SITEADDRESS}",
name: "Parcels",
placeholder: "example: Shawn Smith",
enableSuggestions: true
}],
map: map
}, "search");
search.startup();
});
</script>
</head>
<body>
<div id="search"></div>
<div id="map"></div>
</body>
</html>
Hoping this will help you :)
I'm trying to create a webpage that takes a location via a text box, and plots all recent earthquakes near that location on Google Maps.
I'm using Dreamweaver to debug my code, and the webpage works perfectly when I use the built-in live webpage feature it includes.
However, when I open the saved file in a browser, all I get is an error "Geocode was not successful for the following reason: ERROR". This isn't exactly helpful for figuring out what the issue is, and I have very little experience with web languages and developing web sites.
Any help or insight you can lend me would be greatly appreciated.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXX&sensor=true">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
function codeAddress()
{
var loc = document.getElementById('locText').value;
geocoder.geocode( { 'address': loc}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var north = results[0].geometry.location.lat() + 1;
var south = results[0].geometry.location.lat() - 1;
var east = results[0].geometry.location.lng() + 1;
var west = results[0].geometry.location.lng() - 1;
var url;
url = 'http://api.geonames.org/earthquakesJSON?north=' + north + '&south=' + south + '&east=' + east + '&west=' + west + '&username=jpcguy89';
$.ajax(url,function(quakes)
{
$.each(quakes.earthquakes, function(k, aQuake){
var contentString = '<div id="content">' + '<p><b>ID:</b> ' + aQuake.eqid + '</p>' + '<p><b>Magnitude:</b> ' + aQuake.magnitude + '<p><b>Date:</b> ' + aQuake.datetime + '<p><b>Depth:</b> ' + aQuake.depth + '</div>';
var infowindow = new google.maps.InfoWindow
({
content: contentString
});
var latLng = new google.maps.LatLng(aQuake.lat,aQuake.lng);
var marker = new google.maps.Marker
({
position: latLng,
map: map,
title: 'Earthquake (' + aQuake.eqid + ')'
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
});
});
}
else
{
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<br />
<br />
<div id="test"></div>
<br />
<br />
<form id="geonamesFetch">
City/Location: <input type="text" id="locText" />
<input type="submit" id="submit" onclick="codeAddress()" />
</form>
<div id="map-canvas"/>
<p> </p>
<p> </p>
</body>
</html>
http://jsfiddle.net/mZGL3/
You are binding the click handler in the HTML:
<input type="submit" id="submit" onclick="codeAddress()" />
Done this way, the JavaScript is executed, but then the form is immediately submitted. You need to prevent the form from submitting. Remove the click handler from the html:
<input type="submit" id="submit" />
And bind to the submit handler in your JavaScript so that you can prevent the form from submitting. Add this to your JavaScript:
$(function(){
$("#geonamesFetch").on("submit", function(e) {
e.preventDefault();
codeAddress();
});
});
Demo: jsfiddle.net/mZGL3/3/
Edit: The other problem you have is your call to $.ajax(). That method expects an object, but you are passing a function. You can either change your code to pass an object, setting the function you have now as the success property:
$.ajax(url, {
success: function(quakes) {
...
}
});
Or use $.get(), which accepts a function as the second argument:
$.get(url, function (quakes) {
...
});
Demo: jsfiddle.net/mZGL3/4/
You seem to be loading mixed protocol ressources.
And your jsFiddle seems to have a ressource missing (http://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXX&sensor=true)
Fix your code to access NON httpS .. and try again.
Seen on your jsFiddle :
> Timestamp: 9/30/2013 3:40:41 PM Error: ReferenceError: google is not
> defined Source File: fiddle.jshell.net/mZGL3/show Line: 93
I updated your fiddle here, with the ressource, now, the error is : {"error": "Please use POST request"}
This is a beginners question about web programming. Basically I have a page that shows a default address using the Google Map API. It works fine looking up "221B Baker Street, London, United Kingdom", but there is a textbox that I would like to be able to write an address in and then look it up. It's an cshtml-page and I know of the razor syntax
#{if(IsPost) { do something }}
So basically I would like to take the Request.Form["FindAddress"]; from the textbox and and set it to the javascript myAddress variable so that the users address will be shown instead. But I don't know how to do it inline coding. It keeps giving me syntax errors when placing the IsPost-condition inside the -tag for the javascript functions. Here is the complete page
<!DOCTYPE html>
<html>
<head id="head">
<title></title>
<link href="#Server.MapPath("~/Styles/Site.css")" rel="stylesheet" type="text/css" />
</head>
<script src="http://maps.google.com/maps?file=api&v=2&key=<YOUR_API_KEY>&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
var myAddress = "221B Baker Street, London, United Kingdom"; // how do I overwrite this if it is (isPost)?
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress(myAddress);
}
}
function showAddress(address) {
geocoder.getLatLng(address, function (point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 15); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindow(address); } });
}
</script>
<body onload="initialize()" onunload="GUnload()">
<form id="form1" runat="server">
<div>
<input type="text" id="FindAddress" name="FindAddress" />
</div>
<div id="map" style="width: 500px; height: 500px"></div>
</form>
</body>
</html>
I haven't tried the below code, but I hope it will work. Basically I've put the conditional checking logic outside the script block and store the result in a variable and that is referenced in the javascript.
#{
var address = "221B Baker Street, London, United Kingdom";
if (Request.HttpMethod == "POST")
{
address = Request.Form["FindAddress"];
}
}
<script type="text/javascript">
var myAddress = "#address"; // how do I overwrite this if it is (isPost)?
var map;
var geocoder;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.5, -0.1), 10);
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress(myAddress);
}
}
function showAddress(address) {
geocoder.getLatLng(address, function (point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 15); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindow(address); } });
}
</script>
I'm fairly new at this. I'm trying to build a store locator and trying to figure out how to pass an input value from one page to another page. User would input their zipcode or address in a form on one page and the map and locations would be called on another page using the input.
I'm using ehound store locator platform (sample - here -> http://www.ehoundplatform.com/api/1....nd-google.html)
The map/locator script is this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Store Locator Demo using FreeHound and Google Maps V.3</title>
<style type="text/css">
#map_canvas {
height: 400px;
width:710px;
margin-bottom: 10px;
}
.addressBox {
margin-bottom:10px;
}
</style>
<script type="text/javascript" src="http://www.ehoundplatform.com/api/1.0 /proximity.js?key=xz396aw1qe432q1"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false®ion=AU"></script>
<script type="text/javascript">
var geocoder;
var map;
var bounds;
var markersArray = [];
var infoWindow;
var mapCenterLat = '-28.1594';
var mapCenterLon = '135.6456';
function initialize() {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(mapCenterLat, mapCenterLon),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//initialise single info window to show only one at a time
infoWindow = new google.maps.InfoWindow();
//improve usability by centering map around search point on zoom in/out
google.maps.event.addListener(map, 'zoom_changed', function() { if(mapCenterLat && mapCenterLon) {
setTimeout('centerMap(mapCenterLat, mapCenterLon)', 300);
}
});
}
function addMarkerOverlay(location, title, infoBox, image) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: image
});
marker.setTitle(title);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(infoBox);
infoWindow.open(map, marker);
});
markersArray.push(marker);
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
function searchAroundMe() {
deleteOverlays();
bounds = new google.maps.LatLngBounds();
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//custom marker to mark initial search location
var image = new google.maps.MarkerImage('search_location.png',
// This marker is 32 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the center of the red circle at 16,16.
new google.maps.Point(16, 16)
);
addMarkerOverlay(results[0].geometry.location, 'search spot', 'search initiated from here', image);
bounds.extend(results[0].geometry.location);
var searchLatitude = results[0].geometry.location.lat();
var searchLongitude = results[0].geometry.location.lng();
mapCenterLat = searchLatitude;
mapCenterLon = searchLongitude;
freeHound = new FreeHound( 'showLocs' );
search = new FH_Search();
search.count = 10; //number of locations to be returned in the result set
search.max_distance = 0; //distance limit for proximity search in km, 0 for unlimited
//search from a specific point using latitude and longitude of that point
search.point = new FH_Location( new FH_LatLon( searchLatitude,searchLongitude ) );
//search.filters = new Array();
//search.filters.push( new FH_SearchFilter('cat_id', 'eq', '177') );
search.create_log = false;
freeHound.proximitySearch( search );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function showLocs(response){
if ( response.error_code ) {
alert(response.error_message);
}
if ( response.record_set ) {
//show results in a table
var resultsTable = '<table border="1" cellspacing="0" cellpadding="3" summary="">';
resultsTable += '<tr>';
resultsTable += '<td>#<\/td>';
resultsTable += '<td>Street Address<\/td>';
resultsTable += '<td>Town/Suburb/City<\/td>';
resultsTable += '<td>Postal Code<\/td>';
resultsTable += '<td>State/Province<\/td>';
resultsTable += '<td>Distance<\/td>';
resultsTable += '<td>Longitude<\/td>';
resultsTable += '<td>Latitude<\/td>';
resultsTable += '<\/tr>';
for (var record_count = 0, rl = response.record_set.length; record_count < rl; record_count++ ) {
var record = response.record_set[record_count];
var title = record.details.location_name;
var infoBoxContent = '<strong>Location #'+(record_count+1).toString()+'<\/strong>';
infoBoxContent += '<br \/>'+record.address.street_address+'<br \/>'+record.address.town + ', ' + record.address.postal_code +'<br \/>';
infoBoxContent += 'Distance: '+record.distance.km+'km<br \/>';
addMarkerOverlay(new google.maps.LatLng(record.latitude, record.longitude), title, infoBoxContent, null);
if (record_count < 6) {
bounds.extend(new google.maps.LatLng(record.latitude, record.longitude));
}
resultsTable += '<tr>';
resultsTable += '<td>'+(record_count+1).toString()+'<\/td>';
resultsTable += '<td>'+record.address.street_address+'<\/td>';
resultsTable += '<td>'+record.address.town+'<\/td>';
resultsTable += '<td>'+record.address.postal_code+'<\/td>';
resultsTable += '<td>'+record.address.state+'<\/td>';
resultsTable += '<td>'+record.distance.km+'KM<\/td>';
resultsTable += '<td>'+record.longitude+'<\/td>';
resultsTable += '<td>'+record.latitude+'<\/td>';
resultsTable += '<\/tr>';
}
map.fitBounds(bounds);
resultsTable += '<\/table>';
var resultSet = document.getElementById('resultSet');
resultSet.innerHTML = resultsTable;
}
}
function centerMap(lat,lon) {
var centrePoint = new google.maps.LatLng(lat,lon);
map.setCenter(centrePoint);
}
</script>
</head>
<body onload="initialize()">
<div class="addressBox">
<form action="" onsubmit="searchAroundMe(); return false;">
<input id="address" type="textbox" value="">
<input type="submit" name="search" value="Address Search">
</form>
</div>
<div id="map_canvas"></div>
<div id="resultSet"></div>
</body>
</html>
and the form itself would be on another page. Trying to pull the address input over. This obviously doesn't work
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>KOI Store Locator</title>
</head>
<body>
<div>
<form action="ehound.php" method="post">
<input id="address" name="address" type="textbox">
<input type="submit" name="search" value="Address Search">
</form>
</div>
</body>
</html>
I've looked around on passing inputs via php and such, but this script seems to call on javascript as well and I'm having trouble implementing anything that works. Any help would be greatly appreciated.
Attach a click handler to your form submission button, in the handler simply get the values needed from your form, build a query string with the needed parameters, and window.location.assign("yourotherpage.html?"+theQueryString). Then just pull the query string parameters in the javascript on the other page.
I am not sure what ehound is but in general there are 2 good ways to do this.
You just submitted a form which sends data to the server, so just have the server insert the data you need into the next page.
The specifics of how to accomplish this would be mostly dependant on what server you are using.
Or a non server approach:
store a cookie and then if the other page is on the same domain then you should be able to retrieve it.
Cookies are easy, http://www.quirksmode.org/js/cookies.html (you can skip the long and mildly confusing explanation about the specifics of cookies and just grab the script).
Another way you could pass the information around is in a hidden form element. This qustion is pretty similar and has some good advice.