How to define latitude & longitude instead of address in google map? - javascript

I am displaying Map in my Application.I have added the code below and now the map is displaying correctly for particular city name. My Problem is i need to fetch location by using latitude and longitude of a particular city.
I don't want any new code. Is it possible the get the latitude and longitude values within this code itself by pass #item.Latitude#item.Longitude instead of #item.city
<div class="gMapsCanvas" data-address="#item.city"></div>
<script type="text/javascript">
var GoogleMap = function ga(canvas, address) {
// debugger;
var _parent = this;
//this.location = new google.maps.LatLng(-34.397, 150.644);
var options =
{
center: this.location,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_CENTER
},
streetViewControl: false
};
this.map = new google.maps.Map(canvas, options);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status != google.maps.GeocoderStatus.OK)
return;
_parent.location = results[0].geometry.location;
var marker = new google.maps.Marker(
{
map: _parent.map,
position: _parent.location
});
_parent.resize();
});
};
GoogleMap.prototype.resize = function () {
google.maps.event.trigger(this.map, "resize");
this.map.setCenter(this.location);
}
var Maps = function (classes) {
var _parent = this;
this.maps = new Array();
classes.each(function () {
_parent.maps.push(new GoogleMap($(this).get(0), $(this).attr("data-address")));
});
};
Maps.prototype.resize = function () {
for (var cnt = 0; cnt < this.maps.length; cnt++) {
this.maps[cnt].resize();
}
};
var maps;
</script>
<script type="text/javascript">
$(".tiptext").mouseover(function () {
$(this).children(".description").show();
maps = new Maps($(".gMapsCanvas"));
}).mouseout(function () {
$(this).children(".description").hide();
});
</script>

There are a number of different ways to display Google Maps in your browser.
but the two most easy and good ways are:
1. to Use Goggle MAP API https://developers.google.com/maps/?hl=en
2. Google Polymer as shown below:
<!-- Polyfill Web Components support for older browsers -->
<script src="components/webcomponentsjs/webcomponents-lite.min.js"></script>
<!-- Import element -->
<link rel="import" href="components/google-map/google-map.html">
<!-- Use element -->
<google-map latitude="37.790" longitude="-122.390"></google-map>

Try { 'latlng': latitude + ',' + longitude } instead of { 'address': address }.
I didn't test it but it seems to work according to googlemap webservice api : https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

Related

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>

The followind code is for geo location but it is showing over_query_limit error

I am trying to locate the user and tell him nearest doctors to him but the code is showing over_query_limit. I am not able to resolve the problem as I am new to using API's
I have tried using this code but it is again showing the same problem
{% include 'includes/default.html' %}
<head>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAVZIr_BmEFJTyl7MzSpBS_XpLrBgZEBZg&libraries=places&sensor=false"></script>
<script src="js/script.js"></script>
<!-- <script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script> -->
<!-- <script src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyAVZIr_BmEFJTyl7MzSpBS_XpLrBgZEBZg&callback=initalize" -->
async defer></script>
<script type="text/javascript">
var geocoder;
var map;
var markers = Array();
var infos = Array();
function initialize() {
// prepare Geocoder
geocoder = new google.maps.Geocoder();
// set initial position (Byculla)
var myLatlng = new google.maps.LatLng(14.4426,78.9865);
var myOptions = { // default map options
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('gmap_canvas'),
myOptions);
}
// clear overlays function
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
infos = [];
}
}
// clear infos function
function clearInfos() {
if (infos) {
for (i in infos) {
if (infos[i].getMap()) {
infos[i].close();
}
}
}
}
// find address function
function findAddress() {
var address = '{{location}}';
// script uses our 'geocoder' in order to find location by address name
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) { // and, if everything
is ok
// we will center map
var addrLocation = results[0].geometry.location;
map.setCenter(addrLocation);
// store current coordinates into hidden variables
document.getElementById('lat').value =
results[0].geometry.location.lat();
document.getElementById('lng').value =
results[0].geometry.location.lng();
// and then - add new custom marker
var addrMarker = new google.maps.Marker({
position: addrLocation,
map: map,
title: results[0].formatted_address,
icon: 'marker.png'
});
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
findPlaces();
});
}
// find custom places function
function findPlaces() {
// prepare variables (filter)
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var cur_location = new google.maps.LatLng(lat, lng);
// prepare request to Places
var request = {
location: cur_location,
radius: 2000,
types: ['hospital','doctor']
};
// send request
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
// create markers (from 'findPlaces' function)
function createMarkers(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS)
{
alert('Sorry, nothing is found');
}
}
// creare single marker function
function createMarker(obj) {
// prepare new Marker object
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
// prepare info window
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' +
obj.name +
'<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '
</font>'
});
// add event handler to current marker
google.maps.event.addListener(mark, 'click', function() {
clearInfos();
infowindow.open(map,mark);
});
infos.push(infowindow);
}
// initialization
google.maps.event.addDomListener(window, 'load', initialize);
document.getElementById("doctortab").click();
</script>
</head>
<body onload="findAddress()">
<div id="gmap_canvas" style="position: absolute; top:200px;right:20px
;height:400px;width:800px">
</div>
<input type="hidden" id="lat" name="lat" value="18.9682846" />
<input type="hidden" id="lng" name="lng" value="72.8311396" />
<!-- <input type="hidden" value="{{location}}" id="location"
name='location'> -->
</body>
The expected result is to show the user doctor but it is showing over_query_limit error
If you use Google's geolocation system, last time they made more limits to the free users. You just had to pay for higher connection limits or something like that. Anyway, you didnt posted your code.

Google map marker not showing in bootstrap modal

google map marker not showing in bootstrap modal.
this is my jquery code :
function map_init() {
if(!$('body').data('map')){
var var_mapoptions = {
zoom: 6,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: ['roadmap', 'terrain']
}
};
$('body').data('map',new google.maps.Map($('<div id="map"/>')[0],
var_mapoptions));
}
return $('body').data('map');
}
var Lat;
var lon;
$(document).on('click','a[data-map]',function(){
var data=$(this).data('map'),
map=map_init();
var geocoder = new google.maps.Geocoder();
var address = data;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
Lat = latitude;
lon = longitude;
});
$('#map_modal')
.find('.modal-body')
.append(map.getDiv())
.end()
.find('.modal-title')
.text(data.Name)
.end()
.one('shown.bs.modal',function(){
google.maps.event.trigger(map, "resize");
map.setCenter({lat:Lat,lng:lon});
});
})
.modal('show');
});
it's showing modal , but not showing the map marker. the latitude and longitude values are came from php code( that is from while loop value).
I believe you did not created any Google Maps Javascript API Markers object.
A marker identifies a location on a map. By default, a marker uses a
standard image. Markers can display custom images, in which case they
are usually referred to as "icons."
I would suggest to edit and add this code inside this line:
if ( status == google.maps.GeocoderStatus.OK ) {
//add marker code here
}
code to be added:
var marker = new google.maps.Marker({
positions : new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng() ),
map: map,
title: 'I am a marker :)'
});
And your Marker will appear.

chrome doesnt show google map - javascript

My code works fine in firefox but not word in chrome(chrome doesn't show google map):
http://www.khadamatchi.com/frontend/Index/addAddressByUser
my codes:
getLocation();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
getAddress(lat,lng);
initialize(lat,lng);
}
//START FIND LOCATION
var geocoder = new google.maps.Geocoder();
var marker = null;
var map = null;
function initialize(lat,lng) {
//var $latitude = document.getElementById('latitude');
// var $longitude = document.getElementById('longitude');
var latitude = lat;
var longitude = lng;
var zoom = 16;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
if (marker && marker.getMap) marker.setMap(map);
marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker) {
var latLng = marker.latLng;
// $latitude.value = latLng.lat();
// $longitude.value = latLng.lng();
//console.log( );
getAddress(latLng.lat(),latLng.lng());
});
}
// initialize();
$('#findbutton').click(function (e) {
var address = $("#Postcode").val();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
$(latitude).val(marker.getPosition().lat());
$(longitude).val(marker.getPosition().lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
e.preventDefault();
});
function getAddress(lat,lon)
{
//http://maps.googleapis.com/maps/api/geocode/json?latlng=35.706172,51.316568&sensor=true&language=fa
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat +","+lon + "&sensor=true&language=fa",
success: function(response) {
//Do Something
console.log(response);
var address_components = response.results[0].formatted_address;
$('#address').val(address_components);
},
error: function(xhr) {
//Do Something to handle error
}
});
}
You have two errors here, you are trying to execute some jQuery related code before you download jQuery, resulting in error;
Uncaught ReferenceError: $ is not defined
Example on line 172 $(document).ready(function
Also you are trying to execute some code to the google maps before it is loaded, row 632 var geocoder = new google.maps.Geocoder();
Resulting in error Uncaught ReferenceError: google is not defined
You can move the geocoder inside the initalize function you have or remove the async defer from the <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCfbbmUkl56UuSeZ5nSOwsKTNxplmnheuU&callback=initialize&language=fa" async defer></script>
You also define function initialize twice in the source code, this might bring you some weird issues in the future, each function name should be unique and descriptive about what they do.
UPDATE
For the comment, as you removed the async defer from the google maps loading, can you also remove the &callback=initialize from the src url.
UPDATE 2
Now we've gotten rid of the errors, now there is something weird going on in the function initialize
function initialize()
{
var tehran=new google.maps.LatLng(35.6961111,51.4230556);
var mapProp = {
center:tehran,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myCity = new google.maps.Circle({
center:tehran,
radius:3000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
});
myCity.setMap(map);
}
This does not work, if you replace this with;
function initMap()
{
map = new google.maps.Map(document.getElementById('googleMap'), {
center: {lat: 35.6961111, lng: 51.4230556},
zoom: 13
});
}
initMap();
The map will display correctly, then you can later focus on customising the styles of the map.

change centre of google map with change in city name from action method in controller

I have a simple java script code like this---
<script type="text/javascript">
$(document).ready(function () {
var localityUrl = '#Url.Action("FetchLocalities")';
var subLocalityUrl = '#Url.Action("FetchSubLocalities")';
var localities = $('#SelectedLocality');
var subLocalities = $('#SelectedSubLocality');
$('#SelectedCity').change(function () {
codeAddress();
localities.empty();
subLocalities.empty();
$.getJSON(localityUrl, { ID: $(this).val() }, function (data) {
if (!data) {
// codeAddress();
return;
}
localities.append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, item) {
localities.append($('<option></option>').val(item.Value).text(item.Text));
});
});
})
and my codeAddress function is something like this--
function codeAddress() {
var lat = document.getElementById('SelectedCity').Latitude;
var lng = document.getElementById('SelectedCity').Longitude;
var myLatlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
and my FetchCities action method is---
public List<City> FetchCities()
{
List<City> cities = new List<City>();
cities.Add(new City() { Id = 1 , Name = "--Select Your City--" });
cities.Add(new City() { Id = 2, Name = "Faridabaad", Latitude = 28.4211M, Longitude = 77.3078M });
cities.Add(new City() { Id = 3, Name = "Greater Noida", Latitude = 28.4962M, Longitude = 77.5360M });
return cities;
}
I want to change google map with change in city name by calling the codeAddress function. My problem is that initially google map is loading fine but there is no change in google map with city name changing.You can have a look at full code here http://pastebin.com/6HWcPg9a and my controller is--http://pastebin.com/2zy7fNTj
Plzz tell me is my codeAddress function is correct or not???will it work inside SelectedCity.change(function).What changes to be made if any plzz help me**
Right now, i have tried geocoding feature of google map and tried to pass latitude longitude but failed once again---the code is like this it's not working it's showing some other places on google map--
var address = document.getElementById('SelectedCity').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
As far as I see there are few errors:
There are no methods nor properties like Latitude and Longitude.
You're not populating element with none of this data.
Replace this line:
$.each(data, function (index, item) {
localities.append($('<option></option>').val(item.Value).text(item.Text));
});
with that:
$.each(data, function (index, item) {
localities.append($('<option data-lat='+item.Latitude +' data-lng='+item.Longitude+'></option>').text(item.Text));
});
and this:
var lat = document.getElementById('SelectedCity').Latitude;
var lng = document.getElementById('SelectedCity').Longitude;
with that:
var lat = $('#SelectedCity').data('lat'),
lng = $('#SelectedCity').data('lng');
And one more thing. There is a nice field in MSSQL called dbgeography for storing coordinates with few nice extra properties. Google it ;-)

Categories

Resources