How to find co-ordinates from google map api to display markers from database in map - api

I have a search page in which I am displaying properties from my database as markers in google map. Now I want to modify this search page so that any user will draw either a circle or polygon in the google map and will get properties from our database only in the selected area (drawn by user itself). I am attaching my code so far here.
The circle in the image shows the selected area and the result must display properties available in the selected region. My table contains 2 different fields for latitude and longitude of each property.
Javascript code:
<script type="text/javascript">
var drawingManager;
var all_overlays = [];
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function deleteAllShape() {
for (var i = 0; i < all_overlays.length; i++) {
all_overlays[i].overlay.setMap(null);
}
all_overlays = [];
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function () {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(22, 77),
mapTypeId: google.maps.MapTypeId.HYBRID,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
all_overlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function () {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
google.maps.event.addDomListener(document.getElementById('delete-all-button'), 'click', deleteAllShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The code above contains some events to handle the user interaction in search page to draw cirle,polygone to search property in selected region.
The display property button in the image must show property markers in the selected area.
How would I get the latitude and longitude of selected area of circle or polygon?
How Would I query my database for that range of co-ordinates?
Thanking you very much in advance for your kind help...

I suppose you have found a solution since you post this question.
However, if someone else needs an answer, this is how you can get lat / lng of a drawing polygon :
google.maps.event.addDomListener(drawingManager, 'polygoncomplete', function(polygon) {
var polygonBounds = polygon.getPath();
}
The bounds of each vertices of your polygon are now in polygonBounds, just iterate over it and do what you want with lat / lng
For a circle, you just need lat / lng of the center, and its radius
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
var radius = circle.getRadius();
var center = circle.getCenter();
}
Hope it can help someone
PS : I'm using GoogleMaps v3.14, I never test with other versions.

Related

Global Variables only Called Once then Lost their Scope

I Have a Problem with my Script and hope helping me, and thanks in advance, i still learning javascript and try to learn somthing new everyday, i have a script that draw modeless interface (palette) and have button including (option) that make another new palette (for options), i made the variables as globals for the option palette, but the problem is the global variables is only called once!, and the script lose the global variable scope!.
enter image description here
so my question is how to make the variables not losing its scope and retain in the memory? as long the script run, as an Example if the user move the slider and hit (Show alert due options) its only run once and then lose the scope, even the slider no longer interact with the user and update text box, please test the code to see the problem, and thank again for any help or advice.
Best
M.Hasanain
//Global Variables only Called Once then Lost their Scope!
#targetengine "session1";
var w = new Window("palette", {independent:true}); //Main Palette Windows
var findoptions = new Window("palette"); //Options Palette
function Main() {
// Check to see whether any InDesign documents are open.
// If no documents are open, display an error message.
if (app.documents.length > 0) {
var myDoc = app.activeDocument;
}else{
// No documents are open, so display an error message.
alert("No InDesign documents are open. Please open a document and try again.");
}
}
//---------------------------------------------------------
//Making Palettes Windows
//---------------------------------------------------------
#targetengine "session1";
var w = new Window("palette", {independent:true}); //Main Palette Windows
var findoptions = new Window("palette"); //Options Palette
//gqmanager is the (GREP Query Manager) outside the main Function
w.text = "Test the Connection Between Global Variables and Palettes";
w.preferredSize.width = 500;
w.alignChildren = ["center", "center"]; //"left";
w.orientation = "column"; //"row";
w.spacing = 10;
w.margins = 16;
//Parent - Input Panel Prepare
var InputPanel = w.add("panel", undefined, undefined, { name: "panel1" });
InputPanel.text = "Text Find : ";
InputPanel.preferredSize.width = 1000;
InputPanel.orientation = "row";
InputPanel.alignChildren = ["center", "center"];
InputPanel.spacing = 10;
InputPanel.margins = 16;
//Children - input Panel Inside Prepare
var myInputPanelInside = InputPanel.add("group", undefined, { name: "myInput" });
//--Adding Find What
myInputPanelInside.add("statictext", undefined, "Find What :");
//myInputPanelInside.alignment = "center";
var myGREPString = myInputPanelInside.add("edittext", undefined, "SAMPLE");
myGREPString.helpTip = "Enter Your Text"
myGREPString.characters = 20;
myGREPString.enabled = true;
myGREPString.preferredSize.width = 460;
var Button1 = myInputPanelInside.add("button", undefined, "Options");
//Parent - Radio Panel Prepare
var RadioPanel = w.add("panel", undefined, undefined, { name: "panel2" });
RadioPanel.text = "Select Desired Option : ";
RadioPanel.preferredSize.width = 1000;
RadioPanel.orientation = "row";
RadioPanel.alignChildren = ["center", "center"];
RadioPanel.spacing = 10;
RadioPanel.margins = 16;
//Children - input Panel Inside Prepare
var myRadioPanelInside = RadioPanel.add("group", undefined, { name: "myRadio" });
myRadioPanelInside.preferredSize.width = 500;
myRadioPanelInside.alignChildren = ["center", "center"];
//Adding Radio Buttons
var radio1 = myRadioPanelInside.add("radiobutton", undefined, "Option 1");
var radio2 = myRadioPanelInside.add("radiobutton", undefined, "Option 2");
var radio3 = myRadioPanelInside.add("radiobutton", undefined, "Option 3");
radio1.preferredSize.width = 200;
radio2.preferredSize.width = 200;
radio3.preferredSize.width = 200;
//Previous Default Condition
radio1.value = true;
var myButtonGroup = w.add("group");
myButtonGroup.alignment = "center";
var Button2 = myButtonGroup.add("button", undefined, "Show Alert Due Options");
var Button3 = myButtonGroup.add("button", undefined, "Exit");
Button1.onClick = function () {
CalltheFindOptions();
}
Button2.onClick = function () { Find(); };
function Find() {
doRadioButtonOpt();
}
Button3.onClick = function() {Canceled();};
function Canceled() {
ExitSure();
}
//After Drawing Interface
var a = w.show();
function ExitSure() {
var a = w.close();
exit(0);
}
//User Selection for Radio Buttons
function doRadioButtonOpt() {
myDoc = app.activeDocument;
if (radio1.value == true) {
TestVars();
}
}
function TestVars() {
#targetengine "session1";
var myDoc = app.activeDocument
var TimeMs = Number(SliderControlText.text); //Converting Text to Number
//Show Results Found as User Wish
if (DontShowResults.value == true) { //no Show only Apply
alert("you Select not to Show Results!");
}else{ //Direct Show and Apply
if (ShowResultsDirect.value == true) {
alert("you Select to Show Results in real time!");
}else{ //Show and Apply By WaitinhTime!
if (ShowResults.value == true) { //Show and Apply
alert("you Select to Show Results with Specific time!");
$.sleep(TimeMs); //Wait ms
}
}
}
alert("Do you need somthing else?, try again", "Finish Report");
}
var DontShowResults;
var ShowResultsDirect;
var ShowResults;
var SliderControlText;
var slider;
//--------------------------------------------Building the Find Options Palette-----------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------//
function CalltheFindOptions() {
#targetengine "session1";
//Find Options Window
findoptions.text = "Find Options";
//Parent - Input Panel Prepare
SelectPanel = findoptions.add("panel", undefined, undefined, { name: "panel1" });
SelectPanel.text = " Find Options : ";
SelectPanel.preferredSize.width = 1000;
SelectPanel.orientation = "row";
SelectPanel.alignChildren = ["center", "center"];
SelectPanel.spacing = 10;
SelectPanel.margins = 16;
//Children - input Panel Inside Prepare
mySelectPanelInside = SelectPanel.add("group", undefined, { name: "mySelOpt" });
DontShowResults = mySelectPanelInside.add("checkbox", undefined, "Don't Show Results");
DontShowResults.value = true; //by Default
DontShowResults.alignment = "left";
ShowResultsDirect = mySelectPanelInside.add("checkbox", undefined, "Show Results");
ShowResultsDirect.value = false; //by Default
ShowResults = mySelectPanelInside.add("checkbox", undefined, "Show Results Delayed in milliseconds(Ms) :");
ShowResults.value = false; //by Default
//Adding Slider to Control MS Time
SliderControlText = mySelectPanelInside.add ("edittext", undefined, 10, {readonly: false}); //read only prevent user Entering Nums
SliderControlText.characters = 3;
slider = mySelectPanelInside.add ("slider {minvalue: 1, maxvalue: 100, value: 10}");
//Slider Listener Plus SliderControl Text Listener
slider.onChanging = function () {SliderControlText.text = slider.value;} //Listen to Slider
var c = findoptions.show();
}
If I understand you correctly you need to use as global variables values rather than the objects. And you can change the values of global variables by onClick events.
Here is the bottom part of your code (the rest part of the code wasn't changed):
...
function TestVars() {
#targetengine "session1";
var myDoc = app.activeDocument
var TimeMs = Number(SliderControlText_text); //Converting Text to Number
//Show Results Found as User Wish
if (DontShowResults_value == true) { //no Show only Apply
alert("you Select not to Show Results!");
} else { //Direct Show and Apply
if (ShowResultsDirect_value == true) {
alert("you Select to Show Results in real time!");
} else { //Show and Apply By WaitinhTime!
if (ShowResults_value == true) { //Show and Apply
alert("you Select to Show Results with Specific time!");
$.sleep(TimeMs); //Wait ms
}
}
}
alert("Do you need somthing else?, try again", "Finish Report");
}
// values! not objects
var DontShowResults_value = true;
var ShowResultsDirect_value = false;
var ShowResults_value = false;
var SliderControlText_text = '10';
var slider_value = 10;
//--------------------------------------------Building the Find Options Palette-----------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------//
function CalltheFindOptions() {
#targetengine "session1";
//Find Options Window
findoptions.text = "Find Options";
//Parent - Input Panel Prepare
SelectPanel = findoptions.add("panel", undefined, undefined, {
name: "panel1"
});
SelectPanel.text = " Find Options : ";
SelectPanel.preferredSize.width = 1000;
SelectPanel.orientation = "row";
SelectPanel.alignChildren = ["center", "center"];
SelectPanel.spacing = 10;
SelectPanel.margins = 16;
//Children - input Panel Inside Prepare
var mySelectPanelInside = SelectPanel.add("group", undefined, {
name: "mySelOpt"
});
var DontShowResults = mySelectPanelInside.add("checkbox", undefined, "Don't Show Results");
DontShowResults.value = DontShowResults_value; //by Default
DontShowResults.alignment = "left";
// change the global variable by click
DontShowResults.onClick = function() { DontShowResults_value = DontShowResults.value }
var ShowResultsDirect = mySelectPanelInside.add("checkbox", undefined, "Show Results");
ShowResultsDirect.value = false; //by Default
// change the global variable by click
ShowResultsDirect.onClick = function() { ShowResultsDirect_value = ShowResultsDirect.value }
var ShowResults = mySelectPanelInside.add("checkbox", undefined, "Show Results Delayed in milliseconds(Ms) :");
ShowResults.value = ShowResults_value; //by Default
// change the global variable by click
ShowResults.onClick = function() { ShowResults_value = ShowResults.value }
//Adding Slider to Control MS Time
// SliderControlText = mySelectPanelInside.add("edittext", undefined, 10, {
var SliderControlText = mySelectPanelInside.add("edittext", undefined, SliderControlText_text, {
readonly: false
}); //read only prevent user Entering Nums
SliderControlText.characters = 3;
var slider = mySelectPanelInside.add("slider {minvalue: 1, maxvalue: 100, value: 10}");
// change slider every time as numbers is changes
SliderControlText.onChanging = function() {slider.value = SliderControlText.text};
//Slider Listener Plus SliderControl Text Listener
slider.onChanging = function () {
SliderControlText.text = slider.value;
// change the global variable by onChange
SliderControlText_text = SliderControlText.text;
} //Listen to Slider
findoptions.show();
}
It seems it works as intended.
As far as I can tell (I can be wrong), the cause of the problem was that the objects ShowResultsDirect, ShowResultsDirect, etc, disappears as soon as you close the palette. Because they are elements of the palette. They can't keep values if the palette is closed. That why they worked well only when you open the palette first time.

How to get value for selected place in particular area when draw polyline or polygon through Javascript ArcGIS Api from TileLayer?

Actually I am using ArcGIS API for JavaScript 4.7 and i have a custom internal layer . I want to get name of place particular area when draw polyline the column name is (PLC_NAME) . How to achieve that ?
Suppose I draw a area through polyline. In this area there are places . Now I need to get name of these places .
you can find the using code in below i am using the TileLayer.
require([
"esri/views/MapView",
"esri/Map",
"esri/Basemap",
"esri/layers/TileLayer",
"esri/layers/MapImageLayer",
"esri/widgets/Sketch/SketchViewModel",
"esri/geometry/geometryEngine",
"esri/widgets/CoordinateConversion",
"esri/geometry/support/webMercatorUtils",
"esri/Graphic",
"esri/layers/GraphicsLayer",
"esri/config",
"esri/core/urlUtils",
"esri/widgets/Search",
"esri/tasks/Locator",
"esri/layers/FeatureLayer",
"esri/widgets/Expand",
"dojo/domReady!"
], function (
MapView, Map, Basemap, TileLayer, MapImageLayer,
SketchViewModel,
geometryEngine,
CoordinateConversion,
webMercatorUtils,
Graphic, GraphicsLayer, esriConfig, urlUtils,Search,Locator,FeatureLayer,Expand
) {
esriConfig.request.proxyUrl = "xxxxxxxxxxxxxxx";
urlUtils.addProxyRule({
urlPrefix: "xxxxxxxxxxxxxxxxxxx",
proxyUrl: "xxxxxxxxxxxxxxxxxx"
});
var tempGraphicsLayer = new GraphicsLayer();
var saveGraphicsLayer = new GraphicsLayer();
var updateGraphic;
let highlight = null;
'xxxxxxxxxxxxxxxxxxxxxxxxx';
var myMap;
var layer = new TileLayer({
url: mapUrl
});
var towerLayer = new MapImageLayer({
url: 'xxxxxxxxxxxxxxxxxxxxxxx'
});
myMap = new Map({
layers: [layer, tempGraphicsLayer, saveGraphicsLayer]
});
myMap.add(towerLayer);
view = new MapView({
center: [-55.1683665, 39.951817],
container: "viewDiv",
map: myMap,
zoom: 14
});
var ccWidget = new CoordinateConversion({
view: view
});
// Adds the search widget below other elements in
// the top left corner of the view
view.ui.add(searchWidget, {
position: "top-right",
index: 1
});
view.ui.add(ccWidget, "bottom-left");
view.ui.add("topbar", "top-right");
var pointSymbol = { // symbol used for points
type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
style: "square",
color: "#8A2BE2",
size: "16px",
outline: { // autocasts as new SimpleLineSymbol()
color: [255, 255, 255],
width: 3 // points
}
}
var polylineSymbol = { // symbol used for polylines
type: "simple-line", // autocasts as new SimpleLineSymbol()
color: "#8A2BE2",
width: "4",
style: "dash"
}
var polygonSymbol = { // symbol used for polygons
type: "simple-fill", // autocasts as new SimpleFillSymbol()
color: "rgba(138,43,226, 0.8)",
style: "solid",
outline: {
color: "white",
width: 1
}
}
var polygonBoundrySymbol = { // symbol used for polygons
type: "simple-line", // autocasts as new SimpleFillSymbol()
color: "red"
}
// ################## U R HERE ################## ################## U R HERE ##################
################## U R HERE ##################
let drawBoundry = function(){
//let boundryJson = '&G_GEO_LIMITS.';
let boundryJson = $v('P0_USER_LIMITS');
if(boundryJson){
// let boundry = Graphic.fromJSON(JSON.parse('&G_GEO_LIMITS.'));
let boundry = Graphic.fromJSON(JSON.parse(boundryJson));
boundry.symbol = polygonBoundrySymbol;
tempGraphicsLayer.add(boundry);
return boundry;
}
}
/*
let boundry = drawBoundry();
*/
view.when(function () {
$('.esri-view-root').on('click', '.esri-print__export-button', function(e){
//console.log('event bubbling', e);
//console.log('event bubbling this', this);
e.preventDefault();
saveExportedImg();
});
// create a new sketch view model
var sketchViewModel = new SketchViewModel({
view: view,
layer: tempGraphicsLayer,
pointSymbol: pointSymbol,
polylineSymbol: polylineSymbol,
polygonSymbol: polygonSymbol
});
//setUpClickHandler();
// ************************************************************
// Get the completed graphic from the event and add it to view.
// This event fires when user presses
// * "C" key to finish sketching point, polygon or polyline.
// * Double-clicks to finish sketching polyline or polygon.
// * Clicks to finish sketching a point geometry.
// ***********************************************************
sketchViewModel.on("draw-complete", addGraphic);
sketchViewModel.on("update-complete", addGraphic);
sketchViewModel.on("update-cancel", addGraphic);
sketchViewModel.on("vertex-add", addGraphic);
function addGraphic(evt) {
// console.log ('graphic.geometry',evt.geometry)
//let currentGraphic = popActiveGraphic(tempGraphicsLayer);
let currentGraphic = saveGraphicsLayer.graphics.items.pop();
var geometry = evt.geometry;
var vertices = evt.vertices;
var symbol;
var attr = {
Name: "Selected Area",
X: $v('P24_X'),
Y: $v('P24_Y')
};
// Choose a valid symbol based on return geometry
switch (geometry.type) {
case "point":
symbol = pointSymbol;
break;
case "polyline":
symbol = polylineSymbol;
break;
default:
symbol = polygonSymbol;
break;
}
// Create a new graphic; add it to the GraphicsLayer
// console.log("b4 graphic");
geometry = webMercatorUtils.webMercatorToGeographic(geometry)
/*if(boundry){
var contains = geometryEngine.contains(boundry.geometry, geometry);
var within = geometryEngine.within(geometry, boundry.geometry);
} else {*/
var within = true;
//}
if(within){
let graphic = new Graphic({
geometry: geometry,
symbol: symbol,
//attributes: attr,
popupTemplate: {
title: "{Name}",
content: [{
type: "fields",
fieldInfos: [{
fieldName: "X"
}, {
fieldName: "Y"
}]
}]
}
});
tempGraphicsLayer.add(graphic);
if(currentGraphic){
//currentGraphic.geometry.rings.push(geometry.rings[0]);
geometry.rings.forEach( ring => currentGraphic.geometry.addRing(ring));
//currentGraphic.geometry.addRing(geometry.rings);
//console.log('current active', geometry);
// console.log('current graphic', currentGraphic.geometry);
graphic = currentGraphic;
}
var saveObj = graphic.toJSON();
// console.log('saveObj', saveObj);
$x('P24_JSON').value = JSON.stringify(saveObj);
} else {
apex.message.alert('&G_MAP_BOUNDRY_MSG.');
}
updateGraphic = null;
}
function addMultiGraph(evt1) {
//let currentGraphic = popActiveGraphic(tempGraphicsLayer);
let currentGraphic = saveGraphicsLayer.graphics.items.pop();
var geometry = evt1.geometry;
var vertices = evt1.vertices;
var symbol;
// Choose a valid symbol based on return geometry
switch (geometry.type) {
case "point":
symbol = pointSymbol;
break;
case "polyline":
symbol = polylineSymbol;
break;
default:
symbol = polygonSymbol;
break;
}
//console.log("ring",geometry.rings )
let graphic = new Graphic({
geometry: geometry,
symbol: symbol,
//attributes: attr,
popupTemplate: {
title: "{Name}",
content: [{
type: "fields",
fieldInfos: [{
fieldName: "X"
}, {
fieldName: "Y"
}]
}]
}
});
tempGraphicsLayer.add(graphic);
if(currentGraphic){
geometry.rings.forEach( ring => currentGraphic.geometry.addRing(ring));
}
var saveObj1 = graphic.toJSON();
//console.log('saveObj', graphic);
$x('P24_JSON').value = JSON.stringify(saveObj1);
updateGraphic = null;
}
window.loadGraphic = function(polygon){
if(polygon===undefined || polygon === ''){
console.error('no polygon');
} else {
var graphic = Graphic.fromJSON(JSON.parse(polygon));
if (graphic.geometry){
addMultiGraph(graphic);
//*********************************************************************
view.center.longitude = graphic.geometry.centroid.longitude;
view.center.latitude = graphic.geometry.centroid.latitude;
view.center = [graphic.geometry.centroid.longitude,
graphic.geometry.centroid.latitude];
view.zoom = 12;
}
}
}
// *************************************
// activate the sketch to create a point
// *************************************
var drawPointButton = document.getElementById("pointButton");
drawPointButton.onclick = function () {
// set the sketch to create a point geometry
sketchViewModel.create("point");
setActiveButton(this);
};
// ****************************************
// activate the sketch to create a polyline
// ****************************************
var drawLineButton = document.getElementById("polylineButton");
drawLineButton.onclick = function () {
// set the sketch to create a polyline geometry
sketchViewModel.create("polyline");
setActiveButton(this);
};
var drawPolygonButton = document.getElementById("polygonButton");
drawPolygonButton.onclick = function () {
// set the sketch to create a polygon geometry
sketchViewModel.create("polygon");
setActiveButton(this);
};
// ***************************************
// activate the sketch to create a rectangle
// ***************************************
var drawRectangleButton = document.getElementById(
"rectangleButton");
drawRectangleButton.onclick = function () {
// set the sketch to create a polygon geometry
sketchViewModel.create("rectangle");
setActiveButton(this);
};
document.getElementById("resetBtn").onclick = function () {
sketchViewModel.reset();
tempGraphicsLayer.removeAll();
saveGraphicsLayer.removeAll();
setActiveButton();
drawBoundry();
};
function setActiveButton(selectedButton) {
// focus the view to activate keyboard shortcuts for sketching
view.focus();
var elements = document.getElementsByClassName("active");
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove("active");
}
if (selectedButton) {
selectedButton.classList.add("active");
}
}
// ************************************************************************************
// set up logic to handle geometry update and reflect the update on "tempGraphicsLayer"
// ************************************************************************************
function setUpClickHandler() {
view.on("click", function (evt) {
view.hitTest(evt).then(function (response) {
var results = response.results;
// Found a valid graphic
if (results.length && results[results.length - 1]
.graphic) {
// Check if we're already editing a graphic
if (!updateGraphic) {
// Save a reference to the graphic we intend to update
updateGraphic = results[results.length - 1].graphic;
// Remove the graphic from the GraphicsLayer
// Sketch will handle displaying the graphic while being updated
tempGraphicsLayer.remove(updateGraphic);
sketchViewModel.update(updateGraphic.geometry);
}
}
});
});
}
function errorCallback(error) {
console.log('error:', error);
}
// ************************************************************************************
// returns graphic object if drawn on the map to contcat new graphics to it
// ************************************************************************************
function popActiveGraphic(graphicsLayer){
let length = graphicsLayer.graphics.length;
let count = 0;
if($v('P0_USER_LIMITS').length > 0){
count++;
}
if(length > count){ //active drawing detected
let result = graphicsLayer.graphics.items[length-1];
graphicsLayer.remove(result);
return result;
}
}
});
});
OK, you can resolve the queries on the client or on the server. Depends on your task what options you can pick on.
If you are going to use a spatial query, like the one you mention, and you will apply it on a FeatureLayer, you could solve it on the client. This is a good solution because you already have the features, you are seeing them. Here you have a question whis this situation, how-to-get-get-name-of-hospital-or-street-in-particular-area-when-draw-polyline.
Now, If you need to query something that might not be in your extent (you don't have the features) or you are not using a FeatureLayer, you probably will need to command the server to do this. But don't worry the library has several tools to work with, like QueryTask.
Here you have the same example of the answer link before but using QueryTask.
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1, maximum-scale=1, user-scalable=no'>
<title>Select Feature With Polygon</title>
<style>
html,
body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
#viewDiv {
padding: 0;
margin: 0;
height: 400px;
width: 100%;
}
#namesDiv {
margin: 10px;
height: 200px;
width: 100%;
font-style: italic;
font-weight: bold;
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
color: green;
overflow: auto;
}
</style>
<link rel='stylesheet' href='https://js.arcgis.com/4.15/esri/css/main.css'>
<script src='https://js.arcgis.com/4.15/'></script>
<script>
require([
'esri/Map',
'esri/views/MapView',
'esri/layers/MapImageLayer',
'esri/layers/GraphicsLayer',
'esri/widgets/Sketch/SketchViewModel',
'esri/Graphic',
'esri/widgets/Expand',
'esri/tasks/QueryTask',
'esri/tasks/support/Query'
], function (
Map,
MapView,
MapImageLayer,
GraphicsLayer,
SketchViewModel,
Graphic,
Expand,
QueryTask,
Query
) {
let highlight = null;
const states = new MapImageLayer({
url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer'
});
const queryTask = new QueryTask({
url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2'
});
const polygonGraphicsLayer = new GraphicsLayer();
const selected = new GraphicsLayer();
const map = new Map({
basemap: 'streets',
layers: [states, polygonGraphicsLayer, selected]
});
const view = new MapView({
container: 'viewDiv',
map: map,
center: [-75.1683665, 39.951817],
zoom: 8
});
const sketchViewModel = new SketchViewModel({
view: view,
layer: polygonGraphicsLayer,
pointSymbol: {
type: 'simple-marker',
color: [255, 255, 255, 0],
size: '1px',
outline: {
color: 'gray',
width: 0
}
}
});
sketchViewModel.on('create', function (event) {
if (event.state === 'complete') {
polygonGraphicsLayer.remove(event.graphic);
selectFeatures(event.graphic.geometry);
}
});
const namesDiv = document.getElementById('namesDiv');
view.ui.add('select-by-polygon', 'top-left');
const selectButton = document.getElementById('select-by-polygon');
selectButton.addEventListener('click', function () {
clearUpSelection();
sketchViewModel.create('polygon');
});
function selectFeatures(geometry) {
selected.removeAll();
const query = new Query();
query.returnGeometry = true;
query.outFields = ['*'];
query.geometry = geometry;
queryTask
.execute(query)
.then(function (results) {
const graphics = results.features.map(r => {
r.symbol = {
type: 'simple-fill',
fill: 'none',
outline: {
color: 'cyan',
width: 2
}
};
return r;
});
selected.addMany(graphics);
namesDiv.innerHTML = graphics.map(g => g.attributes.NAME).join(',');
})
.catch(errorCallback);
}
function clearUpSelection() {
selected.removeAll();
namesDiv.innerHTML = null;
}
function errorCallback(error) {
console.log('error:', error);
}
});
</script>
</head>
<body>
<div id='viewDiv'>
<div
id="select-by-polygon"
class="esri-widget esri-widget--button esri-widget esri-interactive"
title="Select counties by polygon"
>
<span class="esri-icon-checkbox-unchecked"></span>
</div>
</div>
<div id="namesDiv"></div>
</body>
</html>
To close I leave you this link to the documentation that explains very well all the possibilities, pros and cons.

Google Places API - Getting Phone Number and Website

I believe I need to make follow up calls to get the results I am looking for. However, I cannot get the phone number and www url for any of the results I pull up.
I am a novice and need some help explaining where in this code I can get the correct results pulled. Please see the demo site here:
http://news.yeselectric.com/gmaps-excel-master/
Here is my JS code:
var store = (function () {
var searchBox,
infowindow,
markers = [],
myLatlng = new google.maps.LatLng(50.0019, 10.1419),
myOptions = { zoom: 6, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl:false },
customIcons = { iconblue: './icons/blue.png' };
var init = function() {
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
input = (document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
searchBox = new google.maps.places.SearchBox((input));
store.listener();
},
listener = function() {
google.maps.event.addListener(searchBox, 'places_changed', function() {
//search for places
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
//set markers zero
markers = [];
$('.addaddress').empty();
//get new bounds
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
store.create_marker(place);
//append to the table
$('.addaddress').append('<tr><td>'+ place.name +'</td><td>'+ place.formatted_address +'</td><td>'+ place.formatted_phone_number +'</td><td>'+ place.website +'</td></tr>');
bounds.extend(place.geometry.location);
}
//set the map
map.fitBounds(bounds);
});
},
create_marker = function(info) {
//create a marker for each place
var marker = new google.maps.Marker({ map: map, icon: customIcons.iconblue, title: info.name, position: info.geometry.location });
//infowindow setup
google.maps.event.addListener(marker, "click", function() {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({content: info.name});
infowindow.open(map, marker);
});
//push the marker
markers.push(marker);
}
return {
init: init,
listener: listener,
create_marker: create_marker
};
})();
google.maps.event.addDomListener(window, 'load', store.init);
Google's API returns different place metadata, depending on which call you're using. To get more place details, you'll need to get the place's placeId and use that to make a call to place.getDetails()
Here's a more thorough answer: https://stackoverflow.com/a/9523345/2141296

Hide ArcGis Markers

We are trying to find suggestions, or implementation options on how to hide a marker once a new point on the map has been clicked.
In our application, once the user clicks on a particular pin on the map, we display a new pin (in a different lat/long location) that is associated with the click event. I.e. a point should be in oklahoma, but the map is displaying texas, so once the marker texas is clicked, a new marker in oklahoma is shown. Our issue is that whenever a user selects a new point, we are not able to "hide" the marker for the previous selection, which then clutters our screen.
Any suggestions on how we could handle this issue?
Code is below:
require(["esri/map", "esri/geometry/Point", "esri/symbols/SimpleMarkerSymbol", "esri/graphic", "dojo/_base/array", "dojo/dom-style", "dojox/widget/ColorPicker", "esri/InfoTemplate", "esri/Color", "dojo/dom", "dojo/domReady!", "esri/geometry/Polyline", "esri/geometry/geodesicUtils", "esri/units","esri/symbols/SimpleLineSymbol"],
function( Map, Point,SimpleMarkerSymbol, Graphic, arrayUtils, domStyle, ColorPicker, InfoTemplate, Color, dom, Polyline, geodesicUtils, Units,SimpleLineSymbol) {
map = new Map("mapDiv", {
center : [-98.35, 35.50],
zoom : 5,
basemap : "topo"
//basemap types: "streets", "satellite", "hybrid", "topo", "gray", "oceans", "osm", "national-geographic"
} );
map.on("load", pinMap);
var arr = [];
var initColor, iconPath;
function pinMap( ) {
map.graphics.clear();
iconPath = "M16,3.5c-4.142,0-7.5,3.358-7.5,7.5c0,4.143,7.5,18.121,7.5,18.121S23.5,15.143,23.5,11C23.5,6.858,20.143,3.5,16,3.5z M16,14.584c-1.979,0-3.584-1.604-3.584-3.584S14.021,7.416,16,7.416S19.584,9.021,19.584,11S17.979,14.584,16,14.584z";
var infoContent = "<b>Id</b>: ${Id} ";
var infoTemplate = new InfoTemplate(" Details",infoContent);
$.post( '{{ path( 'points' ) }}', {}, function( r ) {
arrayUtils.forEach( r.points, function( point ) {
if (point.test==1) {
initColor = "#CF3A3A";
}
else {
initColor = "#FF9900";
}
arr.push(point.id,point.pinLon1,point.pinLat1,point.pinLon2,point.pinLat2);
var attributes = {"Site URL":point.url,"Activity Id":point.id,"Updated By":point.updated,"Customer":point.customer};
var graphic = new Graphic(new Point(point.pinLon1,point.pinLat1),createSymbol(iconPath,initColor),attributes,infoTemplate);
map.graphics.add( graphic );
map.graphics.on("click",function(evt){
var Content = evt.graphic.getContent();
var storeId = getStoreId(Content);
sitePins(storeId);
});
} );
}, 'json' );
}
function getStoreId( content ){
var init = content.split(":");
var fin= init[2].split("<");
return fin[0].trim();
}
function sitePins( siteId ) {
iconPathSite = "M15.834,29.084 15.834,16.166 2.917,16.166 29.083,2.917z";
initColorSite = "#005CE6";
var infoContent = "<b>Distance</b>: ${Distance} Miles";
var infoTemplate = new InfoTemplate(" Distance to Location",infoContent);
var indexValue=0;
for (var index = 0; index < arr.length; index++){
if (arr[index]==storeId){
indexValue =index;
}
}
pinLon1 = arr[indexValue+1];
pinLat1 = arr[indexValue+2];
pinLon2 = arr[indexValue+3];
pinLat2 = arr[indexValue+4];
var line = {"paths":[[[pinLon1, pinLat1], [pinLon2, pinLat2]]]};
line = new esri.geometry.Polyline(line);
var lengths = Number(esri.geometry.geodesicLengths([line], esri.Units.MILES)).toFixed(2);
var attributes = {"Distance":lengths};
var graphicSite = new Graphic(new Point (pinLon1,pinLat1), createSymbol(iconPathSite, initColorSite),attributes,infoTemplate);
var pathLine = new esri.Graphic(line, new esri.symbol.SimpleLineSymbol());
map.graphics.add( pathLine );
map.graphics.add( graphicSite );
}
function createSymbol( path, color ) {
var markerSymbol = new esri.symbol.SimpleMarkerSymbol( );
markerSymbol.setPath(path);
markerSymbol.setSize(18);
markerSymbol.setColor(new dojo.Color(color));
markerSymbol.setOutline(null);
return markerSymbol;
}
} );
</script>
As far as I get the code, it shows the distance between the marker and the point then clicked.You are creating point and polyline on each click event on map. Following can help:
1) Please provide id say 'abc' to polyline, graphic site.
2) Then on every click event remove the graphic and polyline with id 'abc'.
dojo.forEach(this.map.graphics.graphics, function(g) {
if( g && g.id === "abc" ) {
//remove graphic with specific id
this.map.graphics.remove(g);
}
}, this);
3) Then you can create the new polyline and point as you are already doing it.

Plotting Points with the Google Maps API

I have a project where the client is looking to be able to create an outline around a specific area on a Google Map and have it clickable with the standard Google Maps info window.
So rather than just a standard point being plotted at a specific lat and long location it would need to create multiple points and a stroke/outline.
Does anyone know if this is even possible with the Google Maps api?
Thanks.
Sample code:
toggleCommentMode(true);
function toggleCommentMode(isCommentMode){
if(isCommentMode){
//$("#map img").css("cursor", "crosshair !important");
commentModeEventListener = google.maps.event.addListener(FRbase, 'click', commentListener);
}
else{
//$("#map img").css("cursor", "auto !important");
google.maps.event.removeListener(commentModeEventListener);
}
}
//}}}
function commentListener(evt){
var newMarker = new google.maps.Marker({
position: evt.latLng,
draggable : true,
title : "Drag me; Double click to remove",
map : map
});
google.maps.event.addListener(newMarker, 'dragend',function(){
updateMarkerList();
});
google.maps.event.addListener(newMarker, 'dblclick',function(){
$(myMarkers["userComment"]).each(function(i,marker){
if(marker === newMarker){
marker.setMap(null);
Array.remove(myMarkers["userComment"], i);
updateMarkerList();
}
});
});
if(typeof myMarkers["userComment"] == "undefined"){
myMarkers["userComment"] = [];
}
myMarkers["userComment"].push(newMarker);
updateMarkerList();
}
//update marker list
//{{{
function updateMarkerList(){
$("#commentMarkerList").empty();
var path = [];
if(myMarkers["userComment"].length == 0){
$("#commentAccord .step").hide();
}
else{
$("#commentAccord .step").show();
}
$(myMarkers["userComment"]).each(function(i, marker){
path.push(marker.getPosition());
var listItem = $("<li></li>").addClass("ui-state-default").attr("id", i);
$(listItem).mouseenter(function(){
marker.setShadow("img/highlightmarker.png");
});
$(listItem).mouseleave(function(){
marker.setShadow("");
});
var titleLink = $("<a></a>").attr({
innerHTML : "Point",
href : "javascript:void(0);"
});
var removeLink = $("<a></a>").attr({
innerHTML : "(remove this)",
href : "javascript:void(0);"
});
$(removeLink).click(function(){
marker.setMap(null);
Array.remove(myMarkers["userComment"], i);
updateMarkerList();
});
$(listItem).append(
$("<span></span>").addClass("ui-icon ui-icon-arrowthick-2-n-s")
);
$(listItem).append(titleLink).append(removeLink);
$("#commentMarkerList").append(listItem);
});
if(typeof userCommentPolyline != "undefined"){
userCommentPolyline.setMap(null);
}
var polylineopts = {
path : path,
strokeColor : "#FF0000",
strokeWeight : 5,
strokeOpacity : 1
};
userCommentPolyline = new google.maps.Polyline(polylineopts);
userCommentPolyline.setMap(map);
$("#commentMarkerList").sortable({
placeholder: 'ui-state-highlight',
stop : function(evt, ui){
var newList = [];
$("#commentMarkerList li").each(function(i,listitem){
newList.push(myMarkers["userComment"][parseInt($(listitem).attr("id"))]);
});
myMarkers["userComment"] = newList;
updateMarkerList();
}
});
$("#commentMarkerList").disableSelection();
}
//}}}
//clear User comments
//{{{
function clearUserComments(type){
if(typeof myMarkers[type] !== "undefined"){
$(myMarkers[type]).each(function(i,marker){
marker.setMap(null);
});
myMarkers[type]=[];
if(type == "userComment"){
updateMarkerList();
}
}
}
//}}}
//create comments
//{{{
function createComments(){
$.getJSON('data.aspx',
{"p":"commentdata","d":new Date().getTime()},
function(data){
//console.log(data);
$(data).each(function(i,comment){
//console.log(commentTypes[comment.cat_id-1]);
if(typeof commentTypes[comment.cat_id-1] !== "undefined") {
if(typeof commentTypes[comment.cat_id-1].comments == "undefined"){
commentTypes[comment.cat_id-1]["comments"] = [];
}
//create path and anchor from comment.positions
//{{{
var path = [];
var anchor;
$(comment.positions).each(function(i, position){
var pos = new google.maps.LatLng(
position.lat,
position.lng
);
if(position.anchor){
anchor = pos;
}
path.push(pos);
});
//}}}
var isLine = (path.length > 1);
//marker and poly line creation
//{{{
var iconToShow = (isLine)?
commentTypes[comment.cat_id-1].markerLineImage
: commentTypes[comment.cat_id-1].markerImage;
var marker = new google.maps.Marker({
//map : map,
title : commentTypes[comment.cat_id-1].title,
position : anchor,
icon : iconToShow
});
var polyline = new google.maps.Polyline({
path : path,
strokeColor : "#106999",
strokeWeight : 5,
map : null,
strokeOpacity : 1
});
//}}}
//link bar in infowindow creation
//{{{
var zoomLink = $("<a></a>").attr({
href : "javascript:zoomTo("+anchor.lat()+","+anchor.lng()+",16);javascript:void(0);",
innerHTML : "Zoom here"
}).addClass("infowinlink");
var likeLink = $("<a></a>").attr({
href : "javascript:markerVote("+comment.id+",true);void(0);",
innerHTML : "Like"
}).addClass("infowinlink likelink");
var dislikeLink = $("<a></a>").attr({
href : "javascript:markerVote("+comment.id+",false);void(0);",
innerHTML : "Dislike"
}).addClass("infowinlink dislikelink");
var linkBar = $("<div></div>").addClass('linkbar').append(zoomLink).append(" | ")
.append(likeLink).append(" | ")
.append(dislikeLink);
if(isLine){
var showLineLink = $("<a></a>").attr({
href : "javascript:myMarkers["+comment.id+"].line.setMap(map);$('.toggleLineLink').toggle();void(0);",
innerHTML : "Show line",
id : "infowin-showline"
}).addClass("infowinlink toggleLineLink");
var hideLineLink = $("<a></a>").attr({
href : "javascript:myMarkers["+comment.id+"].line.setMap(null);$('.toggleLineLink').toggle();void(0);",
innerHTML : "Hide line",
id : "infowin-hideline"
}).addClass("infowinlink toggleLineLink");
$(linkBar).append(" | ").append(showLineLink).append(hideLineLink);
}
//}}}
//var content = "<div class='infowin'><h4>"+commentTypes[comment.cat_id-1].title +"</h4><p>"+comment.text+"</p>";
var content = "<div class='infowin'><h4>"+comment.name +"</h4><p>"+comment.text+"</p>";
content += $(linkBar).attr("innerHTML")+"</div>";
//marker click function
//{{{
google.maps.event.addListener(marker, 'click', function(){
infoWin.setContent(content);
infoWin.open(map, marker);
currMarkerDom(comment.id);
});
//}}}
var obj = {"marker": marker, "line":polyline};
commentTypes[comment.cat_id-1].comments.push(obj);
myMarkers[comment.id]=obj;
////myMarkers.all = $.map(myMarkers, function (n,i) { return n; });
//myMarkers.all.push(marker);
markerArray.push(marker);
}});
var isLoad = false;
google.maps.event.addListener(map,'tilesloaded', function () {
if (!isLoad) {
isLoad = true;
mc = new MarkerClusterer(map, markerArray, {maxZoom:16});
}
});
}
);
}
//}}}