chrome doesnt show google map - javascript - 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.

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>

google maps user location not loading

I can create a webpage that takes the name, address, lat and long of many businesses in a specific city and have put them into an embedded google map on my page. The connection to the database works, putting up the markers on the map works, however what I can't figure out from any examples, including those on Googles developers page, is how to user a user's location instead of the default coord in the googlemap.js file. What am I missing here?
var map;
var geocoder;
function loadMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}
var marker = new google.maps.Marker({
// position: pune,
map: map
});
var cdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllHonda(allData)
}
function showAllHonda(allData) {
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = data.name;
content.appendChild(strong);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map
});
marker.addListener('click', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
})
})
}
function codeAddress(cdata) {
Array.prototype.forEach.call(cdata, function(data){
var address = data.name + ' ' + data.address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var points = {};
points.id = data.id;
points.lat = map.getCenter().lat();
points.lng = map.getCenter().lng();
updateHondaWithLatLng(points);
} else {
alert('Geocode was not successful for the following reason: ' + status)
}
});
});
}
To find user's position you can use navigator.geolocation :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}

callback function not working

I've created a script that places a marker on a map based on the area you click your mouse over. Once that marker is placed, when your mouse hovers over the marker, an infobox should appear with the address of where the marker is placed. However, the infobox isn't showing up because when I call "info_text", it returns undefined. I realized that I needed to add in a callback function but I don't think I'm implementing it correctly. Could anyone help me fix my code? Thanks
My code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
count = count + 1;
});
} // end of initalize.
function placeMarker_and_attachMessage(position,map)
{
var event = google.maps.event.addListener;
var message = ['This', 'is', 'the', 'secret', 'message'];
var marker = new google.maps.Marker({
position: position,
map: map
});
var pos = info_text(position);
alert('pos is: ' + pos);
var infowindow = new google.maps.InfoWindow({
content: 'hello'
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
function info_text(position)
{
var lat = parseFloat(position.lat());
var lng = parseFloat(position.lng());
alert('lat,lng is: ' + (lat,lng));
var latlng = new google.maps.LatLng(lat,lng);
alert('just before geocode');
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert('in info_text If statement');
if(results[1])
{
alert('in inner if statement');
var finalResult = myCallback(results[1].formatted_address);
return finalResult;
}
else
{
alert('no results found');
}
}
else
{
alert('could not pinpoint location');
}
});
}
function myCallback(loc)
{
alert('i have a location!');
return loc;
}
google.maps.event.addDomListener(window, 'load', initialize);
Your function info_text doesn't return anything, so this line:
var pos = info_text(position);
is where pos is undefined.
You need to include:
return something;
at some point in your function (like you have done further down).
Added
Your function myCallback returns a value, but where it is used:
myCallback(results[1].formatted_address);
it doesn't store the return-value anywhere - it is just discarded.

unable to load two markers on google map from .each loop

am trying to load two markers over the googlemap but it appears that the map is loaded twice and i cant see both of the markers.Here is the code.
var geocoder;
var map;
geocoder = new google.maps.Geocoder();
// var address = document.getElementById("address").value;
// var user='33936357';
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id=33936357,606020001&callback=?", function (data) {
$.each(data, function (i, item) {
var screen_name = item.screen_name;
var img = item.profile_image_url;
var location = item.location;
geocoder.geocode({
address: location
}, function (response, status) {
if (status == google.maps.GeocoderStatus.OK) {
var x = response[0].geometry.location.lat(),
y = response[0].geometry.location.lng();
var mapOptions = {
center: new google.maps.LatLng(x, y),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
icon: img,
title: screen_name,
map: map,
position: new google.maps.LatLng(x, y)
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
});
I dont know how to fix this
Your map creation is within the each loop .. try this :
// setup the map objects
var geocoder = new google.maps.Geocoder();;
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// added this
var bounds = new google.maps.LatLngBounds();
// create the map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id=33936357,606020001&callback=?", function (data) {
$.each(data, function (i, item) {
var screen_name = item.screen_name;
var img = item.profile_image_url;
var location = item.location;
geocoder.geocode({
address: location
}, function (response, status) {
if (status == google.maps.GeocoderStatus.OK) {
var x = response[0].geometry.location.lat(),
y = response[0].geometry.location.lng();
var myLatLng = new google.maps.LatLng(x, y);
var marker = new google.maps.Marker({
icon: img,
title: screen_name,
map: map,
position: myLatLng
});
bounds.extend(myLatLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
map.fitBounds(bounds);
});
Now you create the map one .. add the long and lat to a LatLngBounds object then set the map to fit the Bounds.
Docs on LatLngBounds here

Update Marker Position Google Maps V3

I am quite a novice with javascript stuff and am currently faking it till i make it lol and now ive come across a small hill that i'm struggling to get over :S.
Currently my script finds the users location and adds a pin to the map while copying LatLon to some form fields.
In addition to just zooming in on the users location i would like them to have the ability to add a custom address which is entered into a text field, geocoded and then updates the current pin on the map.
This all works, although it adds an additional pin to the map rather than updating the current pin.
I am unsure how to pass the value from the address geocoding function back into the original pin / or do i delete the original pin and add a new pin. I'm sure i can reuse some functions as well... i don't think my code is terribly efficient :/
Any way i hope a guru out there can help me out
Cheers
Nick
var geocoder;
var map;
var pos;
function initialize() {
geocoder = new google.maps.Geocoder();
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var address = document.getElementById("address").value;
var initialLocation;
var myOptions = {
zoom: 12,
center: initialLocation,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
title: 'Location found using HTML5.',
draggable: true
});
var lat = position.coords.latitude
var lng = position.coords.longitude
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
google.maps.event.addListener(marker, "dragend", function(event) {
var lat = event.latLng.lat()
var lng = event.latLng.lng()
var infowindow = new google.maps.InfoWindow({
content: '<b><?php _e('Latitude:');?></b>' + lat + '<br><b><?php _e('Longitude:');?></b>' + lng
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, "dragstart", function() {
infowindow.close();
});
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in New York.");
initialLocation = newyork;
}
map.setCenter(initialLocation);
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
//-------------------------------------------------------End initialize
function findAddress(address) {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var pos = results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
To 'move' your existing marker, you'll wanna make sure its global and then you can just update its position within the findAddress function with something like:
marker.setPosition(results[0].geometry.location);

Categories

Resources