JS global variable reseting when js function is called from C# - javascript

I create some markers on a google Map. I call the create marker function from c#
for(int a = 0; a<cpt;a++)
{
jsFunc = "myglobalObject.createMarker(" + nearestStations[a][0] + "," + HttpUtility.JavaScriptStringEncode("test", true) + ")";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "script" + a, "$(function () {" + jsFunc + "; });", true);
}
My js looks like this :
var markers = [];
var infoWindowIsSet = false;
myglobalObject = {
map: false,
prev_infowindow: false,
initializeMap: function () {
$(document).ready(function () {
var adresseConnexion = document.getElementById("tbAdresseDefault").value;
var geocoder = new google.maps.Geocoder();
mapOptions = {
zoom: 6,
center: { lat: 46, lng: 1 },
language: "en-US",
mapTypeId: google.maps.MapTypeId.ROADMAP
}
myglobalObject.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
geocoder.geocode({ 'address': adresseConnexion }, function (results, status) {
if (status == 'OK') {
myglobalObject.map.setCenter(results[0].geometry.location);
myglobalObject.createMarker(results[0].geometry.location, "test");
console.log(results[0].geometry.location);
} else {
alert('Adresse incorrecte ');
}
});
});
},
createMarker: function (position, information) {
marker = new google.maps.Marker({
position: position,
map: myglobalObject.map,
});
markers.push(marker);
google.maps.event.addListener(marker, "click", function () {
infowindow = new google.maps.InfoWindow({ content: information });
if (myglobalObject.prev_infowindow) {
myglobalObject.prev_infowindow.close();
}
myglobalObject.prev_infowindow = infowindow;
infowindow.open(myglobalObject.map, this);
infoWindowIsSet = true;
});
google.maps.event.addListener(myglobalObject.map, "click", function () {
if (infoWindowIsSet)
infowindow.close();
});
return marker;
}
}
As you can see, I have a map variable in "myglobalObject" that I set here :
myglobalObject.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
However, after calling the createrMarker func from C#, the variable map seems to be reseted to "false" so the parts where I need it in createMarker are failing. I tried to put map as a global variable and it still failed. What could I do ?
The .cs code :
public string[][] nearestStations = new String[100][];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
parsingXMLDistance();
}
public void parsingXMLDistance()
{
double latOfYourStation = double.Parse(GetLatLng(tbAdresseDefault.Text)[0], CultureInfo.InvariantCulture);
double lngOfYourStation = double.Parse(GetLatLng(tbAdresseDefault.Text)[1], CultureInfo.InvariantCulture);
string latStr, lngStr;
int cpt = 0;
for (int j = 0; j < 100; j++)
nearestStations[j] = new String[1];
string jsFunc;
PDV.pdv_liste l = new PDV.pdv_liste();
l = (litXMLListe("myXMLFile"));
for (int i = 0; i <l.pdv.Length; i++)
{
System.Diagnostics.Debug.Write(i + "\r\n");
if (l.pdv[i].latitude != "" && l.pdv[i].longitude != "") {
if (DistanceTo(latOfYourStation, lngOfYourStation, double.Parse(l.pdv[i].latitude, CultureInfo.InvariantCulture) / 100000, double.Parse(l.pdv[i].longitude, CultureInfo.InvariantCulture) / 100000) < double.Parse(tbDistDefault.Text, CultureInfo.InvariantCulture) )
{
latStr = "" + double.Parse(l.pdv[i].latitude, CultureInfo.InvariantCulture) / 100000;
lngStr = "" + double.Parse(l.pdv[i].longitude, CultureInfo.InvariantCulture) / 100000;
latStr = latStr.Replace(',', '.');
lngStr = lngStr.Replace(',', '.');
nearestStations[cpt][0] = "{lat:" + latStr + ",lng:" + lngStr + "}";
cpt++;
}
}
}
for(int a = 0; a<cpt;a++)
{
jsFunc = "myglobalObject.createMarker(" + nearestStations[a][0] + "," + HttpUtility.JavaScriptStringEncode("test", true) + ")";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "script" + a, "$(function () {" + jsFunc + "; });", true);
}
}

Related

Limit results to defined place types in Google Maps implementation

I would like to display a map that limits nearby results to a category that I designate. I have code that allows for the user to complete their own search, but would like to modify so that the search is disabled and the category is predefined. Source: http://www.gurchet-rai.net/apps/places/
$(document).ready(function(){
var loc;
var map;
var service;
var infoWindow;
var overlays = [];
var resultList = [];
var isMobile = $(window).width < 767;
try {
if (typeof navigator.geolocation !== 'undefined') {
navigator.geolocation.getCurrentPosition (
function(position) {
var coords = position.coords;
loc = new google.maps.LatLng(coords.latitude, coords.longitude);
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
center: loc,
zoom: 13
});
service = new google.maps.places.PlacesService(map);
infoWindow = new google.maps.InfoWindow();
},
function(error) {
if (error.code == 1) {
$('#location-details').append('Please enable location tracking in your web browser');
} else if (error.code == 2) {
$('#location-details').append('Unable to determine location - please ensure location tracking is enabled in your browser');
} else {
$('#location-details').append('Unable to determine location');
}
},
{enableHighAccuracy: true}
);
} else {
$('#location-details').append('Your browser does not support location tracking');
}
} catch (e) {
alert('An error has occured');
}
function plotResultList(){
var iterator = 0;
for(var i = 0; i < resultList.length; i++){
setTimeout(function(){
var lat = resultList[iterator].geometry.location.Za;
var lng = resultList[iterator].geometry.location.Ya;
var name = resultList[iterator].name;
var addr = resultList[iterator].formatted_address;
var reference = resultList[iterator].reference;
var marker = new google.maps.Marker({
position: resultList[iterator].geometry.location,
map: map,
title: name,
animation: isMobile? 'undefined' : google.maps.Animation.DROP
});
overlays.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
var request = {
reference: reference
};
service.getDetails(request, function(place, status){
var content = "<h6>" + name + "</h6>";
if(status == google.maps.places.PlacesServiceStatus.OK){
if(typeof place.rating !== 'undefined'){
var badgeType = '';
if (place.rating < 2){
badgeType = 'badge-important';
} else if (place.rating >= 2 && place.rating <= 3){
badgeType = 'badge-warning';
} else {
badgeType = 'badge-success';
}
content += "<p><small>Rating: <span class='badge " + badgeType + "'>" + place.rating + "</span></small></p>";
}
if(typeof place.formatted_address !== 'undefined'){
content += "<br><small>" + place.formatted_address + "</small>";
}
if(typeof place.formatted_phone_number !== 'undefined'){
content += "<br><small><a href='tel:" + place.formatted_phone_number + "'>" + place.formatted_phone_number + "</a></small>";
}
if(typeof place.website !== 'undefined'){
content += "<br><small><a href='" + place.website + "'>website</a></small>";
}
}
infoWindow.setContent(content);
infoWindow.open(map, marker);
});
});
iterator++;
}, isMobile? 0: (i * 75));
}
}
$('#search').submit(function(e){
e.preventDefault();
var query = $('#query').val();
var request = {
location: map.getCenter(),
radius: '5000',
query: query
};
service.textSearch(request, function(results, status, pagination){
for(var i = 0; i < overlays.length; i++){
overlays[i].setMap(null);
}
resultList.length = 0;
overlays.length = 0;
if (status == google.maps.places.PlacesServiceStatus.OK) {
resultList = resultList.concat(results);
plotResultList();
}
});
});
});
Take a look on Maps Javascript API, specifically in the types parameter. Here are described the allowed types.
Let's say you want to show airports based on user's search, your request will be:
var request = {
location: map.getCenter(),
radius: '5000',
query: query,
types: ['airport']
};

Call google map function in javascript from java code

Basically I want to use the Test.java to call the initMap method from index.js, in order to get the shortest distance from originlist to the destination.
However, when I run the Test.class,
it shows ReferenceError: "Google" is not defined in <eval> at line number 10.
The line is var bounds = new google.maps.LatLngBounds;
public class Test {
public static void main(String []args) throws ScriptException, IOException, NoSuchMethodException {
String[] addres = new String[3];
call("Airport Blvd, Singapore",new String[]{"50 Nanyang Ave, 639798 Singapore","21 Lower Kent Ridge Rd, 119077, Singapore","81 Victoria St, Singapore"});
}
public static void call(String s, String [] sarr)throws ScriptException, IOException, NoSuchMethodException{
StringBuilder sb = new StringBuilder();
sb.append(s+"*");
for(String element:sarr){
sb.append(element + "*");
}
System.out.println(sb.toString().substring(0, sb.toString().length()-1));
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("/Projects/GetShortestDistance/index.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
System.out.println("Testing:"+ inv.invokeFunction("initMap", sb.toString()));
}
}
Here is my javascript refer to the Google Developer
function initMap(longstr) {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
// longstr ='Airport Blvd, Singapore*21 Lower Kent Ridge Rd, 119077, Singapore*50 Nanyang Ave, 639798 Singapore*80 Mandai Lake Rd, 729826*551 bukit timah road'
var array = longstr.split('*');
var destination = array[0];
var origins1 = [];
for(var i =1; i<array.length;i++){
origins1.push(array[i]);
}
var min = "";
var minAddress = null;
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 55.53, lng: 9.4},
zoom: 10
});
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
deleteMarkers(markersArray);
var showGeocodedAddressOnMap = function(asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(bounds.extend(results[0].geometry.location));
markersArray.push(new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
}));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]},
showGeocodedAddressOnMap(true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
if(min > parseFloat(results[j].duration.text.slice(0, -5))){
min = parseFloat(results[j].duration.text.slice(0, -5));
minAddress = originList[i];
}
}
}
}
});
return longstr;
}
function deleteMarkers(markersArray) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
The js works fine in index.html which are able to show the distance and map.

Ajax call slower in MySQL than MS Sql

I'm displaying map in a website with markers. I get the location from mysql database using a servlet and get it in js.
function initMap() {
getLocationFromServlet(xhr); //get
setTimeout(function() {
createMap(); //create map after getting coord from getLocationFromServlet(xhr), but latArray is empty
console.log(latArray); //empty here though defined in getLocationFromServlet
}, 1300);
}
function createMap() {
var mapDiv = document.getElementById('map');
map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0], lngArray[0]));
map.setZoom(17);
createMarker();
setTimeout(function() {
console.log(latArray);
}, 1600)
}
function createMarker() {
latArray.forEach(function(lat, i) {
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>' + '<p style="color:#000000">DeviceID:<p>' + '<p>' + deviceId[i] + '</p>' + '</div>'
});
var marker = new google.maps.Marker({
map: map,
mapTypeId: google.maps.MapTypeId.ROADMAP,
//position: new google.maps.LatLng(latArray[i], lngArray[i]),
icon: "phone6.png"
});
markerArray.push(marker);
markerArray[i].setPosition(new google.maps.LatLng(latArray[i], lngArray[i]));
markerArray[i].addListener("click", function() {
infoWindow.open(map, marker);
});
});
console.log(latArray);
}
function getLocationFromServlet(xhr) {
xhr = new XMLHttpRequest();
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();
xhr.onreadystatechange = function() {
console.log(xhr.readyState == 4); // false twice in console.log, but I call the function only once
if (xhr.readyState == 4) {
data = JSON.parse(xhr.responseText);
//console.log(data);
if (latArrayCount != 1) {
latArray.length = 0;
lngArray.length = 0;
deviceId.length = 0;
} else {
latArrayCount++;
}
for (i = 0; i < data.length; i++) {
if (!((i + 1) % 3 == 0)) {
//console.log(data);
latArray.push(data[i]);
lngArray.push(data[i + 1]);
deviceId.push(data[i + 2]);
i = i + 2;
console.log("lat" + latArray);
}
}
}
}
console.log(latArray); //displayed empty twice before displaying latArray values
}
This code works in ms sql. In mysql i see values in console only after few falses above the console in if (xhr.readyState == 4)

Google geocoder service is not returning appropriate lat and long values with javascript

Google map is not showing the exact location. I'm taking the address from our clients and will display them the map. I cross checked the google lat and long with mine, it is not returning the exact values. Here is my code, if I am wrong, please guide me.
function callMap() {
var fullAddress = address + "," + city + "," + state + "," + zip;
var lat_Company = "";
var lng_Company = "";
geocoder.geocode({
'address': fullAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat_Company = parseFloat(results[0].geometry.location.lat());
lng_Company = parseFloat(results[0].geometry.location.lng());
var lCompanyObject = new Object();
lCompanyObject.Name = companyDetails.CompanyName;
lCompanyObject.Description = address + "<br/>" + city + ", " + state + "," + zip;
lCompanyObject.FullAddress = address + ", " + city + ", " + state + "," + zip;
lCompanyObject.Lat = lat_Company;
lCompanyObject.Lng = lng_Company;
displayCompany(city, state, "comp_map", "mapinfowindow", lCompanyObject, "fromSideBar");
}
});
var abpoutsideBarBuilder = '<ul>' +
'<li><div id="map_wrapper1">' +
'<div id="comp_map1"></div>' +
'<div id="mapinfowindow"style="display:none" ><b>#name</b><br>#description</div></div></li></ul>';
$('.about_map_addr_businesshours').html(abpoutsideBarBuilder);
}
function displayCompany(pCity, pState, pMapDiv, mapinfowindow, lCompany, from) {
var requestLocation = lCompany.FullAddress;
geocoder.geocode({
'address': requestLocation
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = parseFloat(results[0].geometry.location.lat());
var lng = parseFloat(results[0].geometry.location.lng());
if (lat != null && lng != null) {
centerLat = lat;
centerLng = lng;
initDisplayMap(centerLat, centerLng, pMapDiv, mapinfowindow, lCompany, from);
}
} else {
console.error("Geocode was not successful for the following reason ::" + status);
}
});
}
function initDisplayMap(pCenterLat, pCenterLng, pMapDiv, mapinfowindow, pCompany, from) {
if ($("#" + mapinfowindow).length > 0) {
var latlng = new google.maps.LatLng(pCenterLat, pCenterLng);
var myOptions = {
zoom: 14,
center: latlng,
disableDefaultUI: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(pMapDiv), myOptions);
var infowindow = null;
infowindow = new google.maps.InfoWindow({});
var LatLngList = new Array();
var marker = pCompany;
var markerHTML = $('#mapinfowindow').clone().html();
if (from.indexOf("fromSideBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
} else if (from.indexOf("fromAboutBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
}
if (marker.Lat != null && marker.Lng != null) {
var myLatLng = new google.maps.LatLng(marker.Lat, marker.Lng);
LatLngList[LatLngList.length] = myLatLng;
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
clickable: true,
html: markerHTML
});
google.maps.event.addListener(beachMarker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
var bounds = new google.maps.LatLngBounds();
if (LatLngList.length > 1) {
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
//Fit these bounds to the map
map.fitBounds(bounds);
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(beachMarker.getPosition());
}
}
}
}
Don't mix up geocoder an places.
Nakedcherry Waxing Boutique 6th Street Parkhurst,South Africa
the bold part of this string obviously isn't a address-component.
Expecting the desired result is as when I would expect to get my location for a query like
Dr.Molle,Berlin,Germany
The result you get by the geocoder is for 6th Street Parkhurst,South Africa, and the result is correct.
When you look for a place use the places-textsearch, the result for the given query will be: -26.1437060,28.0207660

How to use just some of Geocoded informations

Im trying to change geocoded informations from Schwartmecke 49, 57399 Kirchhundem, Germany to just Schwartmecke 49, Germany , but dont know how. Can anybode help me ? Thanks
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
function initialize() {
var latlng = new google.maps.LatLng(49.624935522974546, 15.46877500000007);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
setupEvents();
centerChanged();
}
function setupEvents() {
reverseGeocodedLast = new Date();
centerChangedLast = new Date();
setInterval(function() {
if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
reverseGeocode();
}
}, 1000);
google.maps.event.addListener(map, 'zoom_changed', function() {
document.getElementById("zoom_level").innerHTML = map.getZoom();
});
google.maps.event.addListener(map, 'center_changed', centerChanged);
google.maps.event.addDomListener(document.getElementById('crosshair'),'dblclick', function() {
map.setZoom(map.getZoom() + 1);
});
}
function getCenterLatText() {
return '(' + map.getCenter().lat() +')';
}
function getCenterLngText() {
return '(' + map.getCenter().lng() +')';
}
function centerChanged() {
centerChangedLast = new Date();
var lat = getCenterLatText();
var lng = getCenterLngText();
document.getElementById('lat').innerHTML = lat;
document.getElementById('lng').innerHTML = lng;
document.getElementById('formatedAddress').value = '';
currentReverseGeocodeResponse = null;
}
function reverseGeocode() {
reverseGeocodedLast = new Date();
geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
}
function reverseGeocodeResult(results, status) {
currentReverseGeocodeResponse = results;
if(status == 'OK') {
if(results.length == 0) {
document.getElementById('formatedAddress').value = 'None';
} else {
document.getElementById('formatedAddress').value = results[0].formatted_address;
}
} else {
document.getElementById('formatedAddress').value = 'Error';
}
}
function geocode() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult(results, status) {
if (status == 'OK' && results.length > 0) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
if(currentReverseGeocodeResponse) {
var addr = '';
if(currentReverseGeocodeResponse.size == 0) {
addr = 'None';
} else {
addr = currentReverseGeocodeResponse[0].formatted_address;
}
text = '<br>' + 'address: <br>' + addr;
}
var infowindow = new google.maps.InfoWindow({ content: text });
}
</script>
Hope i explained my problem enough.
In your reverseGeocodeResult() function, you take the first result and return its "formatted address" property.
Instead of returning this, try browsing its "address_components" property.
See more at
https://developers.google.com/maps/documentation/geocoding/#JSON

Categories

Resources