Google Map not showing,giving error of missing key [closed] - asp.net-mvc

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 3 years ago.
Improve this question
I am new to google maps. I have added the following code to display it :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Marker Clustering</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124},
{lat: -33.848588, lng: 151.209834},
{lat: -33.851702, lng: 151.216968},
{lat: -34.671264, lng: 150.863657},
{lat: -35.304724, lng: 148.662905},
{lat: -36.817685, lng: 175.699196},
{lat: -36.828611, lng: 175.790222},
{lat: -37.750000, lng: 145.116667},
{lat: -37.759859, lng: 145.128708},
{lat: -37.765015, lng: 145.133858},
{lat: -37.770104, lng: 145.143299},
{lat: -37.773700, lng: 145.145187},
{lat: -37.774785, lng: 145.137978},
{lat: -37.819616, lng: 144.968119},
{lat: -38.330766, lng: 144.695692},
{lat: -39.927193, lng: 175.053218},
{lat: -41.330162, lng: 174.865694},
{lat: -42.734358, lng: 147.439506},
{lat: -42.734358, lng: 147.501315},
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=Key&callback=initMap">
</script>
</body>
</html>
It is asking for the key which we have to purchase i think, up to the extent which i have researched about it. can anyone please guide how to solve this key issue or is there any other way which can be used to display the map on website. I do have created the key fromgoogle cloud platform and puted it in required place still the code just shows a glimpse of map and then disappears giving the error for key.
Thanks in advance.

Since you already generated an API key from Google Cloud Platform Console, kindly make sure of the following:
A. Include the API key from the GCP Console like the sample shown below:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=Aiza*******&callback=initMap"></script>
B. Make sure that you have a valid billing account associated to the project where your API key belongs.
If you do not enable your billing account, you will only be able to load your map once per day.
Do not be afraid to add your billing account as you will not be charged unless you upgrade your billing account.
Upon enabling your billing account, you will be entitled to a one time $300 free credit(usable for Google Cloud Platform products) and a monthly recurring $200 free credit(exclusive for Google Maps Platform), in case that you exhaust the free credits, you will receive an OVER_QUERY_LIMIT error and will not be charged, if you wish to not interrupt your usage, you may upgrade your billing account and you will be billed accordingly after you consume all your free credits.
Note: Please also be sure to enable the Maps Javascript API as well.

Try to remove the key parameter from the following resource.
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
It will render the map in development environment. So, that you can develop whatever you want in the development mode.
I have developed google map web application without the key parameter (development environment) which works perfectly.
The map will show the message FOR DEVELOPMENT PURPOSE ONLY in development environment.

Related

Geolocation using IP

I have been trying to find a tool to locate my position using my computer ip.
I have tried some web tools such as http://geoiplookup.net/and https://geoiptool.com/ and some developer tools like freegeoip.net, in which I'm more interested.
the fact is: geolocation is way off in all of them, at least where I'm located (South America, Brazil), all pointing to the same wrong location.
why is it so?
I have tried this piece of code:
send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']
return (lat, lon)
but since it uses a wrong ip it returns some strange lat/lgn, miles away from me.
1) can I pass my exact ip as an argument in the code above?
2) is there any other tool for finding out my precise lat, lng, other than googlemaps?
IP address geolocation is relatively less accurate compare to other geolocation methods such as GPS or WiFi MAC address. The reason is due to frequent reallocate of IP address by ISP.
Reference: http://www.geolocation.com
Back to your questions.
1) The API should auto detect your IP address and return you the estimated location
2) You could not find your precise lat and longitude without enable the GPS
Try the services of http://geoip-db.com
A small jQuery example to retrieve location, country, city, lat, lon, ip and state:
<!DOCTYPE html>
<html>
<head>
<title>GEOIP DB - jQuery example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
</head>
<body>
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
<div>Latitude: <span id="latitude"></span>
<div>Longitude: <span id="longitude"></span>
<div>IP: <span id="IPv4"></span>
<script>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function( location ) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
}
});
</script>
</body>
</html>

How to notify nearby users within a certain location

I've been thinking about this and I couldn't figure it out on how to develop this feature. Currently my app will technically notify every driver, whenever another user trigger a button. I'm using google Maps for calculating routes and so on.
The feature that I'm building is similar like Uber notification system, where whenever a user click "set pickup location" it will then notify to bunch of drivers nearby the user's location.
But the problem right now, it will notify to every drivers that is online, and that's not what I want. I want to notify only the drivers that are nearby to the user's location.
How would I achieve this? What sorts of variables do i need to accomplish this
Im using
IOS/Swift
Google maps
node.js as the backend and socket.io as realtime
Algorithm overview
To notify all the user that are near you, I suggest you the following algorithm:
Determine your location
Determine the location of other users
Calculate their distance to you
This algorithm is very simple, but very heavy, perhaps why #LU_ suggest you do this on your server.
Optimizations
There are multiple hacks to optimize it, for example, instead of checking the location and calculating the distance for all the millions of users in your app, you can elect a random subset, or you can pick and choose who is more interesting based on some criteria.
Steps and Code
The first and second steps of this algorithm require you to find locations. For this effect I suggest you the following example:
https://developers.google.com/maps/documentation/javascript/tutorials/geolocation
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>
Please note that you need to enable your browser to give its location or website/service (I believe StackOverflow may block it, but you can check the original example working on the original page).
Once you have the locations of you and the users you want, you can send this information to the client or to the server. With this information you can then calculate the distances to the original client, using the information described in this discussion Calculate distance between two latitude-longitude points? (Haversine formula) .
With the distances, and the location of the original client, you can then decide what to do.

Gmap4Rails specific location

var handler = Gmaps.build('Google');
handler.buildMap({ internal: {id: 'geolocation'} }, function(){
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(displayOnMap);
});
function displayOnMap(position){
var marker = handler.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude
});
handler.map.centerOn(marker);
};
I can get my current location on the screen by this way. How can I get the specific location that all clients will see the same adress.
For displaying one specific location using Google map API, I think you can work directly with the HTML/CSS portion of your Rails app, insead of having to add a gem.
See this tutorial - https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
and just follow the Rails MVC structure to put your code in the right files. This should also be relatively easier since you have already worked with Geocoder and Gmaps4rails.

ror project ajax load google map issue

I need to use google map service in my ror(ruby on rails)project.However i facing some problems. as we know. we need to include this header to application.html.erb
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE"></script>
<%= link_to 'ajax', boys_ajax_path(:format=>:js), :remote=>true %><div id='ajax' style='width:300px;height:300px;border:1px solid gray'></div>
ajax.js.erb code
$("#ajax").html("<div style='width:100%;height:100%;border:1px solid gray' id='allmaps'></div>")
var map = new google.maps.Map(document.getElementById("allmaps"), {
zoom: 15,
center: new google.maps.LatLng(31.3, 120.6),
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
scaleControl: false,
mapTypeControl: false,
streetViewControl:false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var marker = new google.maps.Marker({ map: map, position: map.getCenter() });
When i first click the ajax button. the google map load success. however when i click twice time. the google map does load. what'wrong with google map. Maybe we should submit google map key every time when we click the ajax button.
Is there any method to solve my problem. send google map key every time when ajax action happen..
There is one gem called gmaps4rails go for it. here

Googlemaps for Rails search for place

Im using Gmaps4Rails gem in my rails app, so I just want to find out if it's possible to search for a place (I dont want to pass coordinates but name of country for example), so i need smth like on the pic below:
See the documentation: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Model-Customization
If you are doing a model based lookup, you would have your address in a field such as gmaps4rails_address. In your case, this would be simply the country.
You could have a boolean field called gmaps and set it to false, indicating that the address (country) has not yet been geocoded. Once it is geocoded, the lat & long will be stored in the appropriate model fields automatically, and the gmaps boolean will be automatically set to true so that the address is not geocoded again.
Update 1:
In response to your comment, your question is misleading. You said you wanted to pass the name of a country, which my solution does (e.g. the gmaps4rails_address field could contain 'Germany'). But it sounds like what you're looking for is to get a map outlining the boundaries of that country, which means you can't use the google maps api (it doesn't do that). So this gem (or any google maps gems) won't help you.
You need to use something like the Google Geomap javascript api. This can't be combined with a regular google map. The Geomap api will give you a flash map with the outlines of the countries.
From the documentation (https://developers.google.com/chart/interactive/docs/gallery/geomap):
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
</head>
<body>
<div id='map_canvas'></div>
</body>

Resources