Google Map API v3 Search Places Starting From My Location? - c#

I need to implement a search for all closes pharmacies starting from my location, the code i wrote sometimes works and sometimes don't, The search always works but what always work is pinning my location and setting it as a starting point in the search.
Sometime when i enter the page for the fist everything works, then after a refresh of the page the lat and long takes the default values that i have set and not My Location, when this happens i open the debug on chrome and trace some lines and suddenly everything works fine, i am not sure what really happens here but hopefully someone could help me cause i am stuck.
Here is my code:
<script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<script>
var map;
var infowindow;
var lat = 26.304295; //29.331647;
var lng = 50.155233; //48.074473;
function success(position) {
};
function error(msg) {
alert(msg);
}
var request = $.ajax({
async: false,
success: function (data) {
navigator.geolocation.getCurrentPosition(function (pos) {
lat = pos.coords.latitude;
lng = pos.coords.longitude;
$("#Lat").val(lat);
$("#Lng").val(lng);
}, function (error) {
// ...
}, { timeout: 10000 });
}
});
$.when(request).done(function () {
function initialize() {
if ($("#Lat").val() != "")
lat = $("#Lat").val();
if ($("#Lng").val() != "")
lng = $("#Lng").val();
var pyrmont = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 14
});
var request = {
location: pyrmont,
radius: 3000,
types: ['pharmacy']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
var myloc = new google.maps.Marker({
clickable: false,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22, 22),
new google.maps.Point(0, 18),
new google.maps.Point(11, 11)),
shadow: null,
zIndex: 999,
map: map
});
var me = new google.maps.LatLng(lat, lng);
myloc.setPosition(me);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
Here is my html code:
<div id="map-canvas">
</div>
<asp:HiddenField runat="server" ClientIDMode="Static" ID="Lat" Value="" />
<asp:HiddenField runat="server" ClientIDMode="Static" ID="Lng" Value="" />

I figured what was the issue here. To be able to get your location you will have to have a fully initialized map first and that is why whenever i tried to get my location it always executes second whatever i do. To solve this problem call get my location function then initialize the map, the map will be initialized first then my location function will be called, after that just point the new long and lat into the map and do you search for places and that is that.
Here is how the code turned out:
<script>
var map;
var infowindow;
var pyrmont;
var lat = 29.331647;
var lng = 48.074473;
function initialize() {
var pyrmont = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 14
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
//Get current location and re-initialize the map to it
//Search starting from your location
//-----------------------------------------------------------------------------------
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
var pyrmont = new google.maps.LatLng(crd.latitude, crd.longitude);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: pyrmont,
zoom: 14
});
var request = {
location: pyrmont,
radius: 3000,
types: ['pharmacy']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
var myloc = new google.maps.Marker({
clickable: false,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22, 22),
new google.maps.Point(0, 18),
new google.maps.Point(11, 11)),
shadow: null,
zIndex: 999,
map: map
});
var me = new google.maps.LatLng(crd.latitude, crd.longitude);
myloc.setPosition(me);
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
//----------------------------------------------------------------------------------------------
//Call get my location
navigator.geolocation.getCurrentPosition(success, error, options);
//Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Related

How to print a map that uses the google maps API on a PDF using Rotativa?

I am using Rotativa in order to obtain a PDF containing information that is previously shown on a Modal, nevertheless, when the user clicks on the button to obtain the PDF, this one does not contain a map that uses the google maps API, is there any way to solve this?
Here is the Modal that is previously shown to the user with the information:
This is the PDF, notice that PDF is not printing the map and it should be there:
Here is my code:
Front-end code
var map = new google.maps.Map($('#map')[0], {
center: { lat: 19.397, lng: -99.144 },
zoom: 10
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(19.397, -99.144),
map: map,
title: ""
});
var bounds = new google.maps.LatLngBounds();
google.maps.event.trigger(map, "resize");
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
marker.setPosition(LatLng);
google.maps.event.trigger(map, 'resize');
map.setCenter(LatLng);
map.setZoom(18);
/*Poligonos*/
var rut = $("#txt_Ruta").val();
var ced = $("#txt_Cedis").val();
var frecu = CosasModal.orden.Frecuencia;
var jqxhr = $.post("/Poligonos/ObtenerPoligono", { "Ruta": rut, "Frecuencia": frecu, "Cedis": ced },
function (data) {
if (data.status == "OK") {
var Poligono = new google.maps.Polyline({
path: data.coordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
Poligono.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: "Ruta " + rut + "<br>Frecuencia: " + frecu + "<br>Cedis: " + ced
});
google.maps.event.addListener(Poligono, 'click', function (event) {
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
var points = Poligono.getPath().getArray();
for (var n = 0; n < points.length; n++) {
bounds.extend(points[n]);
}
map.fitBounds(bounds);
}
});
jqxhr.fail(function () {
//alert("Error de comunicaciĆ³n con el servidor.");
swal("Error", "Error de comunicaciĆ³n con el servidor.", "error");
});
map.fitBounds(bounds);
map.panToBounds(bounds);
/*fin poligonos*/
Rotativa code (imagine that you receive idOrden variable)
var pdf = new ActionAsPdf("ModalPedidosPdfView", new { idOrden = idOrden })
{
FileName = "ReporteOrdenIndividual" + DateTime.Now.ToString() + "_" + idOrden
};
return pdf;
I solved my problem using Select.pdf instead of Rotativa

I"m having of problem using map in mvc application, map is not shown in view while there is no error in working code

<script type="text/javascript">
// Google mapper initialize function
function initialize() {
//To find the current location and add the marker of current location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { $("#message").html("Geolocation is not supported by this browser."); }
function showPosition(position) {
var currentLatLng = position.coords;
var latlon = "Latitude" + currentLatLng.latitude + "," + "Longitude" + currentLatLng.longitude;
//Google map options like langitude, latitude and zoom level
var mapOptions = {
center: new google.maps.LatLng(currentLatLng.latitude, currentLatLng.longitude),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var geocoder = new google.maps.Geocoder;
//Get the element of div to show google maps
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
var control = document.getElementById('floating-panel');
//control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
// adding the user current location to teh marker
addMarker(currentLatLng.latitude, currentLatLng.longitude, "You are here. Please wait. System is locating near by locations");
// Ajax call to get the nearest locations from DB.
jQuery.ajax({
cache: false,
type: "POST",
url: "#Url.Action("GetNearByLocations")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Currentlat: currentLatLng.latitude, Currentlng: currentLatLng.longitude }),
success: function (data) {
//Adding the marker of nearest locations
if (data != undefined) {
$.each(data, function (i, item) {
// addMarker(item["lat"], item["lng"], item["Name"] + " & Distance: " + (Math.round(0.0 + item["Distance"] / 1000)) + " KM");
addMarker(item["lat"], item["lng"], "Click to get directions");
})
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
// Add marker function to add the markers and information window settings
function addMarker(x, y, locationName, distance) {
var infowindow = new google.maps.InfoWindow({
content: locationName
});
var location = new google.maps.LatLng(x, y);
var marker = new google.maps.Marker({
position: location,
map: map,
title: locationName,
});
infowindow.open(map, marker);
// Call the funtion to draw the route map on the clicking on the map marker
marker.addListener('click', function () {
infowindow.open(map, marker);
calculateAndDisplayRoute(directionsService, directionsDisplay, x, y);
});
}
//function to draw the route from the current location to the clicked location on the map
function calculateAndDisplayRoute(directionsService, directionsDisplay, x, y) {
// Origin is user current location
var latlngSource = { lat: parseFloat(currentLatLng.latitude), lng: parseFloat(currentLatLng.longitude) };
//destination is clicked marker on the map
var latlangDestination = { lat: parseFloat(x), lng: parseFloat(y) };
directionsService.route({
origin: latlngSource, //Source
destination: latlangDestination, //destination
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
//show error formats incase the location is not found.
function showError(error) {
if (error.code == 1) {
$("#message").html("User denied the request for Geolocation.");
}
else if (error.code == 2) {
$("#message").html("Location information is unavailable.");
}
else if (error.code == 3) {
$("#message").html("The request to get user location timed out.");
}
else {
$("#message").html("An unknown error occurred.");
}
}
}
// Google maper - starting point
google.maps.event.addDomListener(window, 'load', initialize);
</script>

how do i loop a viewbag list of address in javascript mvc

on my controller i have a list of addresses that i would like to pass to the view so i have the foolowing code that only processes one record but does not loop through each record
<script>
function initMap() {
var uluru = { lat: #ViewBag.Latitude, lng: #ViewBag.Longitude };
//var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: uluru,
// Set mapTypeId to SATELLITE in order
// to activate satellite imagery.
mapTypeId: 'satellite',
zoom: 8
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
Assuming you've assigned a List to the ViewBag
ViewBag.Addresses = new List<Address>() { ... };
One way is to use a for loop to push into a JavaScript array.
<script>
var coordinates = [];
#for(int i = 0; i < ViewBag.Addresses.Count(); i++)
{
<text>
coordinates.push({lat: #ViewBag.Addresses[i].Latitude, lng: #ViewBag.Addresses[i].Longitude });
</text>
}
var map ...
</script>

How to use liScroll JQuery?

I use JavaScript to display bulk on news I did my code well and everything is OK but I need to make the news display from Left to Right. I use JQuery file liScroll .
aspx page
<ul id="ticker02" >
<asp:DataList ID="DLQ" runat="server" RepeatColumns="10" >
<ItemTemplate>
<li><span>...</span><a href='<%#Eval("Art_ID","NewsDetailsPage.aspx?ID="+ Eval("Art_ID"))%>'>
<%# Eval("Title")%></a></li>
</ItemTemplate>
</asp:DataList>
</ul>
JavaScript code
<script type="text/javascript">
$(function () {
$("ul#ticker02").liScroll({ travelocity: 0.05 });
});
</script>
JQuery file :
jQuery.fn.liScroll = function (settings) {
settings = jQuery.extend({
travelocity: 0.20
}, settings);
return this.each(function () {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripWidth = 1;
$strip.find("li").each(function (i) {
stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width
$strip.width(stripWidth);
var totalTravel = stripWidth + containerWidth;
var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo) {
$strip.animate({ left: '-=' + spazio }, tempo, "linear", function () { $strip.css("left", containerWidth); scrollnews(totalTravel, defTiming); });
}
scrollnews(totalTravel, defTiming);
$strip.hover(function () {
jQuery(this).stop();
},
function () {
var offset = jQuery(this).offset();
var residualSpace = offset.left + stripWidth;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
});
Add <li class="classname">
Then
Use this :
jQuery.fn.liScroll = function (settings) {
settings = jQuery.extend({
travelocity: 0.20
}, settings);
return this.each(function () {
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripWidth = 1;
$strip.find('.classname').each(function (i) { <-- Change Here
stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width
$strip.width(stripWidth);
var totalTravel = stripWidth + containerWidth;
var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo) {
$strip.animate({ left: '-=' + spazio }, tempo, "linear", function () { $strip.css("left", containerWidth); scrollnews(totalTravel, defTiming); });
}
scrollnews(totalTravel, defTiming);
$strip.hover(function () {
jQuery(this).stop();
},
function () {
var offset = jQuery(this).offset();
var residualSpace = offset.left + stripWidth;
var residualTime = residualSpace / settings.travelocity;
scrollnews(residualSpace, residualTime);
});
});

google maps multi marker info window not working

I'm using Google Maps API on my web page. I'm try to add multiple markers to the page with info windows. The markers get added ok, but the info windows all have the info for the last marker. any ideas?
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://testserver/se1/WebServices/ShelterWebService.asmx" />
</Services>
</asp:ScriptManager>
<asp:LinkButton ID="BtnHome" runat="server" onclick="BtnHome_Click">Home</asp:LinkButton>
<div id="map_canvas"></div>
<script type="text/javascript">
var geocoder;
var map;
var addresses;
function GetShelters() {
ShelterExpress.WebServices.ShelterWebService.GetShelters('', OnGetSheltersComplete);
}
function OnGetSheltersComplete(retValue) {
addresses = new Array();
for (x in retValue) {
addresses.push(retValue[x]["Address"]);
}
GenerateMap();
}
function GenerateMap() {
/* Create the geocoder */
geocoder = new google.maps.Geocoder();
/* Some initial data for the map */
mapOptions = {
zoom: 10
, center: new google.maps.LatLng(0, 0)
, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//var infowindow = new google.maps.InfoWindow();
var marker, i;
if (geocoder) {
for (var item in addresses){
geocoder.geocode({ 'address': addresses[item] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
/* Position the map */
map.panTo(results[0].geometry.location);
/* Put a marker */
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: addresses[item]
});
var infowindow = new google.maps.InfoWindow({ content: addresses[item] });
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
});
}
}
}
$(document).ready(function() {
GetShelters();
});
I'm guessing that you've copied an object or an array. You'll need to provide more information on addresses[item]
In javascript, copying something like a string or a boolean gives an actual copy, but copying an object or an array only gives a reference.
var foo = [1, 2, 3];
var bar = foo;
bar[1] = 5;
alert(foo[1]);
// alerts 5
EDIT FOR NEW INFORMATION: If you have jQuery loaded, a quick way to clone JS objects is to use $.extend()
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
for an array you could just use javascript's slice()
a = [1];
b = a.slice();
It will depend on what retValue[x]["Address"] IS and which libraries you have loaded.

Categories

Resources