Add markers after removing them from Google Maps - javascript

I want to add new markers after removing markers from Google maps. However, my code isn't doing what I expected. After the removal, no new marker could be added.
Code snippet:
function codeAddress(coordinates) {
console.log("called");
var myLatlng = new google.maps.LatLng(coordinates.lb,coordinates.mb);
var marker = new google.maps.Marker({
map: map,
position: myLatlng
});
markersArray[markerid] = marker;
markerid++;
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
markersArray = {};
markerid = 0;
}
function go(){
var cMin = document.getElementById('costMin').value;
var cMax = document.getElementById('costMax').value;
var religion = document.getElementById('religion').value;
// remove previous marker layer
deleteOverlays();
console.log(coorList.length);
for(var i = 0; i < coorList.length; ++i){
//codeAddress();
if(religion != ""){
if(coorList[i].cost1 >= cMin && coorList[i].cost1 <= cMax && coorList[i].religion.toLowerCase() ==religion.toLowerCase()){
codeAddress(coorList[i]);
}
}
else{
if(coorList[i].cost1 >= cMin && coorList[i].cost1 <= cMax){
codeAddress(coorList[i]);
}
}
}
}
<input id="costMin" type="textbox" >
<input id="costMax" type="textbox" >
<input id="religion" type="textbox" >
<input type="button" value="Go" onclick="go();">
When I placed a console.log("called") within the codeAddress() function, it seems like the function is not called at all after the click. If I get rid of deleteOverlays() from the go() function, the codeAddress will be called. Is there anything wrong with my code?

Related

Implementing pointInpolygon search algorithm on Bing Maps with location's coordinate coming from database

I wish to determine if a given point(latitude and longitude) is found within a drawn polygon on a Bing map or not. The polygon is drawn by the user.
This is what I already have
<script type='text/javascript'>
var map, drawingManager;
function GetMap() {
map = new Microsoft.Maps.Map('#myMap', {});
//Load the DrawingTools module
Microsoft.Maps.loadModule('Microsoft.Maps.DrawingTools', function () {
//Create an instance of the DrawingTools class and bind it to the map.
var tools = new Microsoft.Maps.DrawingTools(map);
//Show the drawing toolbar and enable editing on the map.
tools.showDrawingManager(function (manager) {
//Store a reference to the drawing manager as it will be useful later.
drawingManager = manager;
//Create a shortcut to the DrawingBarAction to minimize code.
var da = Microsoft.Maps.DrawingTools.DrawingBarAction;
//Limit which tools appear in the drawing toolbar.
manager.setOptions({
drawingBarActions: da.polyline | da.polygon | da.erase,
fillColor: 'rgba(255, 0, 0, 0.5)'
});
});
});
}
function IsPointInPolygon() {
var shapes = drawingManager.getPrimitives();
if (shapes && shapes.length > 0) {
for (i = 0; i < shapes.length; i++) {
var points = shapes[i].getLocations();
//Get all locations from DB
$.ajax({
url: 'http://localhost:53851/Locations/ReturnLocationsList',
type: 'POST',
dataType: 'json',
success: function (response) {
//do something with data
//alert(JSON.stringify(response.data));
arrayLocations = response.data;
//alert(arrayLocations.length);
var columns = ['IdLocation', 'Name', 'Latitude', 'Longitude'];
//Convert gotten locations to Maps.Locations in order to ease calculations
var allLocations = [];
alert("are you here ?");
for (i = 0; i < arrayLocations.length; i++) {
var coordinates = new Microsoft.Maps.Location(arrayLocations[i].Latitude, arrayLocations[i].Longitude);
allLocations.push(coordinates);
}
alert(allLocations[0]);
//Add pushpin to each location coming from DB
var pinLocation = new Microsoft.Maps.Pushpin(origin, {
color: 'blue'
});
for (i = 0; i < allLocations.length; i++) {
map.entities.push(pinLocation);
if (pointInPolygon(points, allLocations[i].Latitude, allLocations[i].Longitude)) {
alert("Point is inside polygon");
}
else {
alert("Point is not found in polygon");
}
}
function pointInPolygon(points, lat, lng) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var inside = false;
for (var i = 0, j = points.length - 1; i < points.length; j = i++) {
var intersect =
points[i].latitude > lat != points[j].latitude > lat &&
lng <
((points[j].longitude - points[i].longitude) *
(lat - points[i].latitude)) /
(points[j].latitude - points[i].latitude) +
points[i].longitude;
if (intersect) inside = !inside;
}
return inside;
}
},
error: function (error) {
//log or alert the error
alert("There's an error !");
//alert(error);
}
});
}
//return locations;
} else {
alert("No shapes in the drawing manager.");
}
}
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[Bing Map key]' async defer></script>
<div class="row">
<div class="col-lg-12">
<div id="myMap" style="position:relative;width:950px;height:500px;"></div>
<input type="button" class="btn btn-primary" value="Get Shapes" onclick="IsPointInPolygon()" />
</div>
</div>
The arrayLocations are locations actually coming from the database and within these locations are at least one found in the drawn polygon area, but I definitely get the "Point not found in polygon" message, for all the locations.
I even tried adding pushpins to each of the locations coming from the database, but the pushpins won't display on the map.
I'm completely lost. Please for any help!
It appears you adapted the Polygon Search algorithm from official documentation, right? If so, their implementation is appears to be buggy and is not working as expected.
Instead i would propose to utilize the following one to determine whether the point is actually inside the polygon:
function pointInPolygon(points, lat, lng) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var inside = false;
for (var i = 0, j = points.length - 1; i < points.length; j = i++) {
var intersect =
points[i].latitude > lat != points[j].latitude > lat &&
lng <
((points[j].longitude - points[i].longitude) *
(lat - points[i].latitude)) /
(points[j].latitude - points[i].latitude) +
points[i].longitude;
if (intersect) inside = !inside;
}
return inside;
}
Demo
var map, drawingManager, point;
function GetMap() {
map = new Microsoft.Maps.Map("#myMap", {});
point = map.getCenter();
var pin = new Microsoft.Maps.Pushpin(point, {
title: "Center point"
});
map.entities.push(pin);
//Load the DrawingTools module
Microsoft.Maps.loadModule("Microsoft.Maps.DrawingTools", function() {
//Create an instance of the DrawingTools class and bind it to the map.
var tools = new Microsoft.Maps.DrawingTools(map);
//Show the drawing toolbar and enable editing on the map.
tools.showDrawingManager(function(manager) {
//Store a reference to the drawing manager as it will be useful later.
drawingManager = manager;
//Create a shortcut to the DrawingBarAction to minimize code.
var da = Microsoft.Maps.DrawingTools.DrawingBarAction;
//Limit which tools appear in the drawing toolbar.
manager.setOptions({
drawingBarActions: da.polyline | da.polygon | da.erase,
fillColor: "rgba(255, 0, 0, 0.5)"
});
});
});
}
function getShapes() {
var shapes = drawingManager.getPrimitives();
if (shapes && shapes.length > 0) {
for (i = 0; i < shapes.length; i++) {
var points = shapes[i].getLocations();
if (pointInPolygon(points, point.latitude, point.longitude)) {
alert("Point is inside polygon");
} else {
alert("Point is not found in polygon");
}
}
//return locations;
} else {
alert("No shapes in the drawing manager.");
}
}
function pointInPolygon(points, lat, lng) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var inside = false;
for (var i = 0, j = points.length - 1; i < points.length; j = i++) {
var intersect =
points[i].latitude > lat != points[j].latitude > lat &&
lng <
((points[j].longitude - points[i].longitude) *
(lat - points[i].latitude)) /
(points[j].latitude - points[i].latitude) +
points[i].longitude;
if (intersect) inside = !inside;
}
return inside;
}
<div id="myMap" style="position:relative;width:640px;height:320px;"></div>
<input type="button" class="btn btn-primary" value="Get Shapes" onclick="getShapes()" />
<script
type="text/javascript"
src="https://www.bing.com/api/maps/mapcontrol?key=Ap12Gwv9esg5iXgfAh5Ehlbf36MZ-O8051Sl66Zm6glGwq7PSaaKgGPpcOUEGICy&callback=GetMap"
async
defer
></script>

Google maps api filter checkbox [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to make google map with filtering. One filter is select box (for now it is working) and other filer is with check boxes. So now my it have behavior as a radio button. You can se example here http://extrol.ellectadigital.com/distributeri/.
When you check it, it shows good pin, but when you click on the second it removes the first pin, and I don't want that.
So here is my code :
`http://codepen.io/PoznanM/pen/VpoZOm`
Problem is here onclick="filterChecker(this.value);" in filterChecker function only single checked item was compared and other marker are cleared.
So you have to compare all the checked items. I added function selectAllChecked() which passes checked values as array to function filterChecker()
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var filters = {
shower: false,
vault: false,
flush: false
}
// Our markers
markers1 = [
['0', 'Title', 44.741318, 20.433573, 'Beograd', 'distributer'],
['1', 'Title', 45.823783, 16.024404, 'Zagreb', 'servis'],
['2', 'Title', 44.438350, 17.631215, 'Bosna', 'maloprodaja']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(45.662477, 18.022074);
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.662477, 18.022074),
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var tip = marker[5];
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
tip: tip,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
var get_set_options = function() {
ret_array = []
for (option in filters) {
if (filters[option]) {
ret_array.push(option)
}
}
return ret_array;
}
var filter_markers = function() {
set_filters = get_set_options()
// for each marker, check to see if all required options are set
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// start the filter check assuming the marker will be displayed
// if any of the required features are missing, set 'keep' to false
// to discard this marker
keep = true
for (opt = 0; opt < set_filters.length; opt++) {
if (!marker.properties[set_filters[opt]]) {
keep = false;
}
}
marker.setVisible(keep)
}
}
// Fuction for checkboxes
var tipovi = document.getElementsByClassName('chk-btn').value;
var selectAllChecked = function() {
var checkedPlace = []
var allCheckedElem = document.getElementsByName('filter');
for (var i = 0; i < allCheckedElem.length; i++) {
if (allCheckedElem[i].checked == true) {
checkedPlace.push(allCheckedElem[i].value)//creating array of checked items
}
}
filterChecker(checkedPlace) //passing to function for updating markers
}
var filterChecker = function(tip) {
//console.log(tip);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
//console.log(marker);
if (in_array(this.marker.tip, tip) != -1) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
#map-canvas {
height: 300px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<div id="map-canvas">
</div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Izaberite Mesto</option>
<option value="Beograd">Beograd</option>
<option value="Zagreb">Zagreb</option>
<option value="Bosna">Bosna</option>
</select>
<div id="buttons">
<input type="checkbox" name="filter" value="distributer" class='chk-btn' onclick="selectAllChecked();">
<label for='shower'>Distributer</label>
<input type="checkbox" name="filter" value="maloprodaja" class='chk-btn' onclick="selectAllChecked();">
<label for='flush'>Maloprodaja</label>
<input type="checkbox" name="filter" value="servis" class='chk-btn' onclick="selectAllChecked();">
<label for='vault'>Servis</label>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmUfKutqGZ-VgbD4fwjOFd1EGxLXbxcpQ&sCensor=false"></script>

HTTP Request inside a function not works

I have this controller for AngularJS Framework.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var locations =[]; var map; var markers = [];
$scope.mappa = function(){
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.507033, lng: 15.080257},
zoom: 8
});
}
$scope.insert = function(){
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data)
{locations = data;});
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i<markers.length; i++){
markers[i].setVisible(true);
}
};
In html file, i have a button that calls the insert function.
But if I run this code, the button works at the second time only. Instead if the http request is out of the function, the button works immediatly. Why?
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data)
{locations = data;});
$scope.insert = function(){
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i<markers.length; i++){
markers[i].setVisible(true); }
};
It's asynchronous method. Move the code insert into callback success.
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data) {
var marker, i;
for (i = 0; i < data.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i][0], data[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i<markers.length; i++){
markers[i].setVisible(true); }
}
});
But if I run this code, the button works at the second time only.
It works at the first time, it's just AJAX request is asynchronous, so the location variable is not populated yet by the time your are trying to use it. When you click next time, it turns out that data has already loaded and location is set and "cached".
You need to do your stuff in callback function:
$scope.insert = function () {
$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati").success(function (data) {
var marker, i, locations = data;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
markers.push(marker);
}
for (i = 0; i < markers.length; i++) {
markers[i].setVisible(true);
}
});
};
And finally, when you make it work, consider moving your request logic into reusable service, making requests in controller is not the best design:
$scope.insert = function () {
locations.get().then(function(data) {
var marker, i, locations = data;
// ...
});
};

Google map not getting centered

The google map i am using does not get centered about the mean point i have calculated.
The code for the initialization is given. The map appears to be zoomed out a lot and its center far off from the center i have calculated. The mean appears in the extreme top left of the map. What is the problem here?
I am displaying the map in Bootstrap modal.
function initializeMap()
{
var xMean = 0.0;
var yMean = 0.0;
for(var i=0;i<points.length;i++)
{
xMean += parseFloat(points[i][0]);
yMean += parseFloat(points[i][1]);
}
xMean /= parseFloat(points.length);
yMean /= parseFloat(points.length);
var myMean = new google.maps.LatLng(xMean, yMean);
var mapOptions = {
zoom:17,
center:myMean
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i<points.length;i++) {
path.push(new google.maps.LatLng(points[i][0],points[i][1]));
bounds.extend(path[i]);
};
map.fitBounds(bounds);
//Displaying the markers
var marker;
for (var i = 0; i < path.length; i++) {
marker = new google.maps.Marker({
position: path[i],
map: map
});
}
//Displaying the path
for (var i = 0; i<path.length-1; i++) {
var start = path[i];
var end = path[i+1];
requestDirections(start,end);
}
}
by using:
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
you seem to overwrite myMean coordinates

Rectangular Overlays appearing only after dragging the map

I have a lot of markers and I m using markerClusterer to display them on the map.Additionally on click of a checkbox I need to display a rectangular overlay (title) near all these markers.
I have written 2 functions as follows for creating the overlay and deleting it.
function createLabel(posi,name){
posicion = etiquetaNombre.length;
etiquetaNombre[posicion] = name;
var label = new Label({
position:posi,
map: map,
text:name
});
rectangleNombre[posicion]=label;
rectangleNombre[posicion].setMap(map);
console.log("add: etiquetaNombre",etiquetaNombre);
myfun();
}
function deletelabel(name){
for(var i = 0; i < etiquetaNombre.length; i++){
if(etiquetaNombre[i] == name){
rectangleNombre[i].setMap(null);
rectangleNombre.splice(i, 1);
etiquetaNombre.splice(i, 1);
}
}
console.log("delete marker"+name);
console.log("delete: etiquetaNombre",etiquetaNombre);
myfun();
}
I m invoking the createLabel function as follows:
var markerImage = new google.maps.MarkerImage(imageUrl,
new google.maps.Size(24, 32));
var latLng = new google.maps.LatLng(40, -100);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(40, -100),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < 10; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var div=document.createElement('div');
var marker = new google.maps.Marker({
position: latLng,
draggable: false,
map: map,
title:"marker"+i
});
posi=marker.position;
name=marker.title;
createLabel(latLng,name);
markers.push(marker);
}
markerClusterer = new MarkerClusterer(map, markers);
Since I am using markerClusterer I had to customize it for my above requirement.I had done it as below.
Cluster.prototype.addMarker = function(marker) {
/// some lines
if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
// Min cluster size not reached so show the marker.
marker.setMap(this.map_);
posi=marker.position;
name=marker.title;
createLabel(posi,name);
}
if (len == this.minClusterSize_) {
// Hide the markers that were showing.
for (var i = 0; i < len; i++) {
this.markers_[i].setMap(null);
name=this.markers_[i].title;
deletelabel(name);
}
}
if (len >= this.minClusterSize_) {
marker.setMap(null);
name=marker.title;
deletelabel(name);
}
this.updateIcon();
return true;
};
The myfun() is called on click of check box is as below.
function myfun(){
var element=document.getElementById('id1');
if(element.checked){
for(var i = 0; i < etiquetaNombre.length; i++){
var div = document.getElementById('normal-'+etiquetaNombre[i]);
if(div!=null){
div.style.display = "";
}
}
console.log("in my fun element checked",etiquetaNombre);
}
google.maps.event.addListener(map, 'bounds_changed', function () {
if(element.checked){
for(var i=0; i<etiquetaNombre.length; i++){
var div = document.getElementById('normal-'+etiquetaNombre[i]);
if(div!=null){
div.style.display = "";
}
}
}
});
}
The problem which I m facing here is that on zooming when the clustered markers are disintegrated the rectangular overlays do not appear for them.But on simply dragging the map it appears.Can anybody guide what I m doing wrong here.
[Edited]
function createLabel(xCenter , yCenter, nombre,banderaPersonalizada){
posicion = etiquetaNombre.length;
etiquetaNombre[posicion] = nombre;
var RectangleBounds = new google.maps.LatLngBounds(new google.maps.LatLng(yCenter,xCenter), new google.maps.LatLng((yCenter+1),(xCenter+1)));
rectangleNombre[posicion] = new RectangleNombre(RectangleBounds);
rectangleNombre[posicion].setMap(map);
}
function RectangleNombre(bounds, opt_weight, opt_color) {
this.bounds_ = bounds;
this.weight_ = opt_weight || 2;
this.color_ = opt_color || "#888888";
}
RectangleNombre.prototype = new google.maps.OverlayView();
RectangleNombre.prototype.onAdd = function(map) {
var idDiv = "normal-"+etiquetaNombre[posicion];
var div = document.createElement("div");
div.id = idDiv;
div.innerHTML = '<span style=" color:blue; font-family:arial; font-size:7.5pt; font-weight:900" > '+etiquetaNombre[posicion]+'</span>';
div.style.position = "absolute";
console.log("banderaCheckEtiqueta"+banderaCheckEtiqueta);
if(banderaCheckEtiqueta){
div.style.display = "";
} else {
div.style.display = "none";
}
this.getPanes().mapPane.appendChild(div);
this.map_ = map;
this.div_ = div;
}
RectangleNombre.prototype.draw = function() {
var proj = this.getProjection();
var c1 = proj.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var c2 = proj.fromLatLngToDivPixel(this.bounds_.getNorthEast());
this.div_.style.width = "0px";
this.div_.style.height = "0px";
this.div_.style.left = c1.x - 12;
this.div_.style.top = c1.y + 2;
}

Categories

Resources