How to find accurate LatLng values of google map - javascript

In my App,user can find place Name using click event,after getting place Name,I am showing the place name to user with inputFieldFor this I written the following code.
//helper function
function makingGeocodeRequest(obj,callback){
var geocodeInstance=new google.maps.Geocoder();
geocodeInstance.geocode(obj,callback);
}
google.maps.event.addListener(mapInstane,"click",function(event){
makingGeocodeRequest(_.object(["location"],[event.latLng]),
function(res,status){
document.getElementById("field").value=res[0]["formatted_address"];
}
)
})
Once user click on Save button.I am finding latlng value based on place Name.using the following code
makingGeocodeRequest(
_.object(["address"],[document.getElementById("field").value]),
function(res,status){
if (status===google.maps.GeocoderStatus.OK) {
var latLngObj=res[0]["geometry"]["location"];
console.log(latLngObj;
}
}
)
The problem here,both latlng values are different(click event time latlng value and save button action latlng value).
Actually both are finding from Google,but it's returning different latlng values.
While click event event,I am changing cursor style with this Icon.After click on Save button reverting default cursor.
How can I fix this.Can anyone help me.
Thanks.

To solve your problem you can create and array of points, add marker to this array and render results of the array on the map.
Here is how you can do this :
With Javascript,
<script type="text/javascript">
var map;
var markersList= [];
function initGMap()
{
var latlng = new google.maps.LatLng(39, 20);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
// add a click event handler to the map object and get the lat Lng and then place it on the map
google.maps.event.addListener(map, "click", function(event)
{
// place a marker
placeMarker(event.latLng);
// display the lat/lng in your form's lat/lng fields
document.getElementById("latVal").value = event.latLng.lat();
document.getElementById("lngVal").value = event.latLng.lng();
});
}
// here is the function to place Marker on the map
function placeMarker(location) {
// first remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// add marker in markers array
markersList.push(marker);
//map.setCenter(location);
}
// Here you can use this function to delete all markers in the array
function deleteOverlays() {
if (markersList) {
for (i in markersList) {
markersList[i].setMap(null);
}
markersList.length = 0;
}
}
</script>
With Html code,
<body onload="initGMap()">
<div id="map"></div>
<input type="text" id="latVal">
<input type="text" id="lngVal">
</body>

Related

Unable to use google maps Markers, and issue with javascript Global variables

I want to make a page where the user keeps entering latitude and longitude values, and these places are plotted on the map and route between these is gained.
Initially, i am trying to plot markers on the map by taking latitude and longitude values from the user.
My html is like this:
<div>
<label for = "lat">Enter Latitude</label>
<input id="lat" type="text" name="lat">
<label for = "lat">Enter Longitude</label>
<input id="lng" type="text" name="lng">
<button id ="submit">Submit</button>
</div>
<div id="map"></div>
My css is like this:
<style>
/*Set the height explicitly.*/
#map {
height: 400px;
width: 100%
}
</style>
And i am using Google Map javascript like this.
<script src="https://maps.googleapis.com/maps/api/js?key=myAPIKey&callback=initMap" async defer></script>
And my script is like this:
<script>
var map=0;
function initMap(){
var pesCollege = {lat:12.9345, lng:77.5345};
map = new google.maps.Map(document.getElementById('map'), {
center:pesCollege,
zoom: 10
});
console.log("Inside initMap");
console.log(map); //this is printing map properties
return map;
// var marker = new google.maps.Marker({position: pesCollege, map : map});
//This marker works if uncommented!
}
plot();
function plot(){
console.log("inside plot function")
console.log(map); //this is printing 0, i.e. global variable map is not
//loaded with map inside initMap
// var latlng = new google.maps.LatLng(latitude, longitude);
var pesCollege = {lat:12.9345, lng:77.5345};
var marker = new google.maps.Marker({position: pesCollege, map :map});
//I want this marker to work.
// var marker = new google.maps.Marker({position: latlng,setMap: map});
console.log("Marker set")
}
If this works, then i think i can pass latitude and longitude values to plot the markers by adding event listener like this:
var button = document.getElementById('submit')
button.addEventListener("click", function(){
var dict = {};
var latitude = document.getElementById('lat').value;
var longitude = document.getElementById('lng').value;
x = parseInt(latitude);
y = parseInt(longitude);
dict['lat']=latitude;
dict['lng']=longitude;
var cdns = JSON.stringify(dict);
// alert("hi");
alert(cdns);
console.log(dict);
console.log(cdns);
plotPoint(x,y); //this is a similar funtion to plot() but i send l&l values, not sure if i can pass them like this.
plot();
});
and my plotPoint(x,y) is like this
function plotPoint(latitude,longitude){
var latlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({position: latlng,map: map});
console.log("Marker set")
}
I already read a lot of git answers but none resembled my problem. Any help would be greate. Thanks in advance.
I have reduced the code you provided to the minimum so that it plots a Marker when submitting the lat/lng pair.
You should be doing further checks though. The code, as it is, will fail if you don't provide a latitude and/or longitude and hit submit.
Here is a working code snippet. I have added comments, please read them.
var map;
function initMap() {
// Default map location
var pesCollege = {
lat: 12.9345,
lng: 77.5345
};
// Create the map and center on deault location
map = new google.maps.Map(document.getElementById('map'), {
center: pesCollege,
zoom: 10
});
// Create a Marker at the default location
var marker = new google.maps.Marker({
position: pesCollege,
map: map
});
var button = document.getElementById('submit');
button.addEventListener("click", function() {
// Get latitude and longitude values from inputs
var latitude = document.getElementById('lat').value;
var longitude = document.getElementById('lng').value;
// Are you sure about that?
// This will return an integer, ie. 12.3452 will become 12
latitude = parseInt(latitude);
longitude = parseInt(longitude);
// Send the values
plotPoint(latitude, longitude);
});
}
function plotPoint(lat, lng) {
// Create a LatLng with the given coordinates
var pos = new google.maps.LatLng(lat, lng);
// Create a Marker at the given coordinates
var marker = new google.maps.Marker({
position: pos,
map: map
});
// Pan the map to see your added Marker
map.panTo(pos);
}
#map {
height: 400px;
width: 100%
}
<div>
<label for="lat">Enter Latitude</label>
<input id="lat" type="text" name="lat">
<label for="lat">Enter Longitude</label>
<input id="lng" type="text" name="lng">
<button id="submit">Submit</button>
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
To add a bit more info:
In the API call, you have added callback=initMap which will execute the initMap function once the API script has finished loading. All Google Maps related code should be initialized in this function as otherwise you might be calling Google Maps methods before it has finished loading which will error.
You should always refer to the official documentation for properties and methods.
You should watch your Javascript console for errors.

Multiple google map on modal view Ruby on Rails

I have a list of enterprices and need to display a map on their respective modal, for this I have this:
<div class="row" id="googleMap<%=enterprice.id%>" style="width 100%; height: 300px;" data1='<%=enterprice.latitud%>' data2='<%=enterprice.longitud%>'>
</div>
this code is on a html.erb file.
My function for loading the map:
<script>
function myMap(lat, long) {
var uluru = { lat: lat, lng: long};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
And a jquery helper for passing the data
$(document).on("ready", function() {
$('#googleMap<%=enterprice.id%>').each(function (index, element) {
var $this = $(element);
myMap($this.attr("data1"), $this.attr("data2"));
});
});
The problem is the map is only loading on the modal for the first cell, but not actually displaying any map.
And the other cells wont even load the map.
First of all, you don't need a map and a modal for each. You can have one and change them using JS. This way you will not overload your page with elements you will only use in series but never together in parallel.
You can have a map defined in your modal whenever the page is ready.
<script>
var map;
var old_marker;
function initMap() {
var point = {lat: 0, lng: 0};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: point,
mapTypeId: 'terrain'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(point);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
if(old_marker){
old_marker.setMap(null)
}
old_marker = marker
markers.push(marker);
map.setCenter(location);
}
</script>
Now we have to add a marker for each enterprise just by clicking on them.
I suggest adding a certain class to them
$(document).on("ready", function() {
initMap();
$(.enterprise).click(function(){
addMarker($this.attr("data1"), $this.attr("data2"));
});
});
By this, a marker will be added on the click on each enterprise and the map will focus that location. Now all you need to do is show the Modal.
References: https://developers.google.com/maps/documentation/javascript/examples/marker-remove

Set marker on Google Map when changing a checkbox

I need some help regarding the Google Maps API. I was able to initialize the map. Now I want to add some markers to it.
I have a set of checkboxes (they are called "networks"). Each checkbox has a hidden longitude and latitude field. If the checkbox is checked, a marker should be displayed on the map
I managed to do this with the detour, of clicking on the map. But I want to trigger the creation of new markers on change of the checkbox.
Here is how it works, when I click on the map the markers appear:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 48.7791, lng: 9.0367}
});
google.maps.event.addListener(map, "click", function(event) {
//Get all checked Networks
var checked_network = $( ".checkbox-network:checked" );
checked_network.each(function(){
network_id = $( this ).data("network-id");
//Get the hidden location longitudes and latitudes for each checked network element
network_locations_latitude = $(".location_latitude_network_"+network_id).val();
network_locations_longitude = $(".location_longitude_network_"+network_id).val();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(network_locations_latitude,network_locations_longitude),
map: map
});
});
});
}
Here is how I try to get it to work, with clicking on the checkboxes. Unfortunately nothing happens. The marker object shows up in the JavaScript console, but on the map no markers appear.
$(document).on('change','.checkbox-network', function() {
var checked_network = $( ".checkbox-network:checked" );
checked_network.each(function(){
network_id = $( this ).data("network-id");
//Get the hidden location longitudes and latitudes for each checked network element
network_locations_latitude = $(".location_latitude_network_"+network_id).val();
network_locations_longitude = $(".location_longitude_network_"+network_id).val();
console.log(network_id + " - " + network_locations_latitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(network_locations_latitude,network_locations_longitude),
map: map,
title: "test"
});
console.log(marker);
});
});
What am I missing? How can I show the markers in the google-map with the onchangeevent of the checkboxes?
You have to initialize map variable globally. Currently scope of map variable only available inside initMap() function.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 48.7791, lng: 9.0367}
});
$(document).on('change','.checkbox-network', function() {
var checked_network = $( ".checkbox-network:checked" );
checked_network.each(function(){
network_id = $( this ).data("network-id");
//Get the hidden location longitudes and latitudes for each checked network element
network_locations_latitude = $(".location_latitude_network_"+network_id).val();
network_locations_longitude = $(".location_longitude_network_"+network_id).val();
console.log(network_id + " - " + network_locations_latitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(network_locations_latitude,network_locations_longitude),
map: map,
title: "test"
});
console.log(marker);
});
});
In the second snippet of your code, the map isn't defined because it's been defined in the scope of initMap(). I wonder why Google doesn't throw any errors.
change your initMap like below; move the map object to the global scope to be accessible from all scope (I always use this for my own projects)
initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 48.7791, lng: 9.0367}
});
}
Here you should be more logical with the name map, so replace it with another name to avoid further conflicts.

Google Maps not centering after dynamically loading latitude/longitude on click

I'm dynamically loading latitude/longitude variables and passing them to the Google Maps Initialize(); function.
function initialize() {
var lat = $('.map_img', '.inview').attr('data-lat');
var lng = $('.map_img', '.inview').attr('data-lng');
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.trigger(map, 'resize');
}
So I'm pulling these coordinates via the data attribute, which is set via a wordpress widget and giving them to Google Maps.
I want to run the function, getting new coordinates every time the user clicks these left/right buttons.
previous
next
$('.btn-prev').click(function () {
//initialize maps script again
initialize();
});
$('.btn-next').click(function () {
//initialize maps script again
initialize();
});
Then the user clicks on a Map image which opens the large map with the new coordinates.
var mapImg = $('.map_img');
var $overlay = $('.overlay'),
resize = true,
map;
mapImg.click(function () {
$overlay.show();
if (resize) {
initialize();
resize = false;
}
});
The problem I'm having is that after the first click the Map is not centered. I had assumed google.maps.event.trigger(map, 'resize'); would solve this problem.
I'm not sure why this is happening so I've created a fiddle to replicate the issue.
http://jsfiddle.net/SEOplay/3CXSs/13/
Help much appreciated.
Try using:
google.maps.event.addDomListener(window, "click", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Not efficient code because I'm not excatly sure how it fits into your code, but it will recenter the map every time someone clicks somewhere. It should give you some idea of the code you need, if you have any trouble let me know.
JSFiddle (you also seem to have a bug where it doesn't change the map on the first next/prev click.

How to set google map marker by latitude and longitude and provide information bubble

The following sample code provided by google maps api
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
the following only shows google map of the location without a marker.
I was wondering how I can place a marker by giving latitude/longitude parameters?
And how is it possible to store my own information pulled from a database on that marker?
Here is a JSFiddle Demo that shows you how to set a google map marker by Lat Lng and also when click would give you an information window (bubble):
Here is our basic HTML with 3 hyperlinks when clicked adds a marker onto the map:
<div id="map_canvas"></div>
<a href='javascript:addMarker("usa")'>Click to Add U.S.A</a><br/>
<a href='javascript:addMarker("brasil")'>Click to Add Brasil</a><br/>
<a href='javascript:addMarker("argentina")'>Click to Add Argentina</a><br/>
First we set 2 global variables. one for map and another an array to hold our markers:
var map;
var markers = [];
This is our initialize to create a google map:
function initialize() {
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
We then create 3 lat lng locations where we would like to place our markers:
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
Here we create a function to add our markers based on whatever is passed onto it. myloc will be either usa, brasil or argentina and we then create the marker based on the passed param. With in the addMarker function we check and make sure we don't create duplicate marker on the map by calling the for loop and if we the passed param has already been created then we return out of the function and do nothing, else we create the marker and push it onto the global markers array. After the marker is created we then attach an info window with it's associated marker by doing markers[markers.length-1]['infowin'] markers.length-1 is just basically getting the newly pushed marker on the array. Within the info window we set the content using html. This is basically the information you put into the bubble or info window (it can be weather information which you can populate using a weather API and etc). After info window is attached we then attach an onclick event listener using the Google Map API's addListener and when the marker is clicked we want to open the info window that is associated with it by calling this['infowin'].open(map, this) where the map is our global map and this is the marker we are currently associating the onclick event with.
function addMarker(myloc) {
var current;
if (myloc == 'usa') current = usa;
else if (myloc == 'brasil') current = brasil;
else if (myloc == 'argentina') current = argentina;
for (var i = 0; i < markers.length; i++)
if (current.lat() === markers[i].position.lat() && current.lng() === markers[i].position.lng()) return;
markers.push(new google.maps.Marker({
map: map,
position: current,
title: myloc
}));
markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
content: '<div>This is a marker in ' + myloc + '</div>'
});
google.maps.event.addListener(markers[markers.length - 1], 'click', function() {
this['infowin'].open(map, this);
});
}
When all is done we basically attach window.onload event and call the initialize function:
window.onload = initialize;

Categories

Resources